开发者

Code First Entity Framework

We are using Miscrosoft's code first entity framework (4.1) to map to an existing database. We want to be able to change the datatypes and values of some properties that map one to one with a table. For instance, there is a column on the table that determines if a record is current. It is an integer column, and has values 1 or 2. We don't want to change the database as there are many different applications fetching data from that colum, but it would be nice for our code to have the class that maps to that table have a bool propert开发者_如何学Cy that is IsActive, which returns true if the table column is 1 and false otherwise. Is there a way to configure the EnityFrame work so that we can define this mapping directly without having two properties on the actual class, one for the integer column (mapped to the database) and one boolean property computed from the other? Can I map the boolean property directly to the integer column?


Simple answer is no. EF is totally stupid in this area and it is completely missing simple type mapping.

That means that you cannot change type of scalar properties and your class indeed has to work with that int property using values 1 and 2 to define your IsActive.

The workaround can be:

public class YourClass
{
    public int IsActiveValue { get; set; }
    [NotMapped]
    public bool IsActive
    {
        get { return IsActiveValue == 2; }
        set { IsActiveValue = value ? 2 : 1; }
    }
}

This workaround has some disadvantages

  • You must have two properties and IsActvieValue must be visible to context
  • You cannot use IsActive in linq-to-entities queries
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜