实体框架4.1代码优先从两个数据库列映射/填充单个属性 [英] 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.
我正在使用现有数据库创建ASP.NET MVC 3应用程序,但想先编写代码,所以我使用EF Power Tools CTP1入门.最终,我将重构为一个更好的解决方案,但是要开始使用,我使用MVCScaffolding
生成了控制器和视图.我正在努力在模型上创建显示值(FullName
)属性,该属性是数据库中FirstName
和LastName
列的组合.
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 MVCScaffolding
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.
我有一个简单的课程
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; }
}
和看起来像
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
}
}
是否可以创建FullName
映射,还是我要以完全错误的方式进行此操作?
Is it possible to create the FullName
mapping or am I going about this the entirely wrong way?
推荐答案
否,无法创建FullName
映射.但是您可以使用以下简单的解决方法:
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; }
}
此方法的唯一缺点是您不能在linq-to-entities查询中使用FullName
属性(因此,例如,您无法使用FullName
进行订单或搜索-您仍必须使用FirstName
和LastName
).
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
).
如果您使用新的Power Tools的代码生成功能,则应按照@Steve Mallory的建议,在单独的部分类中声明此属性-如果要重新生成,请不要修改生成的代码.
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.
这篇关于实体框架4.1代码优先从两个数据库列映射/填充单个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!