这里是MVC的新手,所以对可能是一个愚蠢的问题道歉。
我为现有数据库创建了一些数据库优先实体框架模型,这种模型运行良好。其中一个模型从数据库中提取名字和姓氏,我可以在我的代码中引用它。
namespace manage.mysite.com.DataModels
{
using System;
using System.Collections.Generic;
public partial class UserProfile
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public UserProfile()
{
this.webpages_Roles = new HashSet<webpages_Roles>();
this.Property_Info = new HashSet<Property_Info>();
}
public string Email { get; set; }
public int UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string TelNumber { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<webpages_Roles> webpages_Roles { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Property_Info> Property_Info { get; set; }
}
}
然后我在lastName下添加了另一个字符串,将它们绑在一起:
public string FullName {
get
{
return FirstName + " " + LastName;
}
}
这非常完美,除了每次我需要从数据库更新模型的问题,这显然会被覆盖。我如何阻止这种情况发生?
答案 0 :(得分:2)
使用NotMapped
属性:
[NotMapped]
public string FullName {
get
{
return FirstName + " " + LastName;
}
}
即使用Data Annotations。如果您更喜欢Fluent Api,那就是这样:
modelBuilder.Entity<UserProfile>().Ignore(t => t.FullName);
使用分部类以避免每次从DB更新模型时丢失自定义属性:
public partial class UserProfile
{
[NotMapped]
public string FullName {
get
{
return FirstName + " " + LastName;
}
}
}