开发者

Entity Framework 4.1 Code First mapping/populating a single property from two db columns

I know this question has been asked/answered but I can't find it for the life of me.

I am creating and ASP.NET MVC 3 app with an existing db but wanted to go code first so I'm used the EF Power Tools CTP1 to get me started. Ultimately, I will refactor to a better solution but to get going I used the MVCScaff开发者_开发百科olding to gen up controllers and views. I'm struggling with creating a display value (FullName) property on my model that is a combination of the FirstName and LastName columns in the DB.

I have a simple class

public class Manager
{
    public Manager(){}

    public int ManagerID { get; set; }

    [DisplayName] // Not in db.. want to populate this from first & last name 
    public  string FullName { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

and a mapping file that looks like

     public ManagerMap()
    {
        // Primary Key
        this.HasKey(t => t.ManagerID);

        // Table & Column Mappings
        this.ToTable("Manager");
        this.Property(t => t.ManagerID).HasColumnName("ManagerID");

        this.Property(t => t.FirstName).HasColumnName("FirstName");
        this.Property(t => t.LastName).HasColumnName("LastName");
        this.Property(t => t.Email).HasColumnName("Email");
        this.Property(t => t.FullName).WhatToDo..? //<-- Can I / how does this mapping look

    }
}

Is it possible to create the FullName mapping or am I going about this the entirely wrong way?


No it is not possible to create FullName mapping. But you can use this simple workaround:

public class Manager
{
    public Manager(){}

    public int ManagerID { get; set; }

    [NotMapped]
    public string FullName 
    { 
       get
       {
           return FirstName + " " + LastName;
       }
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
}

The only disadvantage of this approach is that you cannot use FullName property in linq-to-entities query (so you cannot for example order or search by FullName - you must still use FirstName and LastName).

If you use code generation feature of new Power Tools you should really declare this property in separate partial class as proposed by @Steve Mallory - don't modify generated code if you ever want to regenerate it.


I wouldn't map the field in the database. Instead, I would declare my POCO as partial. In another file, I would have the same partial class and define the combination value there (with only a getter). I have sample code if you need it.

Keeping it in a separate file helps if you do any code generation later.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜