在EF中保存数据时,是否始终必须包含虚拟属性?

时间:2014-10-07 01:50:58

标签: entity-framework

我的用户看起来像这样:

public class User 
{
    public User() 
    {
        Subscribers = new List<SubscriberNumber>();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int UserId { get; set; }
    public string Username { get; set; }

    [Required]
    public virtual BusinessNumber BusinessNumber { get; set; }
    public string BusinessName { get; set; }
    public int SubscriberCount { get; set; }

    public List<SubscriberNumber> Subscribers { get; set; }
}

由于一些未公开的EntityValidationError:

,以下调用失败
var user = db.Users.First(s => s.Username == username);
user.BusinessName = "test";
db.SaveChanges();

但要么在VS中打开user.BusinessNumber,要么使用以下内容:

var user = db.Users.Include(s => s.BusinessNumber).First(s => s.Username == username);

SaveChanges()开始工作。在更新用户时,是否始终必须包含虚拟属性?这看起来很麻烦......

1 个答案:

答案 0 :(得分:0)

属性上的虚拟允许EF构建代理。在EF的常规属性上使用虚拟来读取和写入数据并不是必需的。但是,导航属性需要Virtual。 默认Context.Configuration.ValidateOnSaveEnabled = true;
EF将在SaveChanges()上触发验证。

所以在导航属性为必需的示例中(为什么?)您必须首先在上下文和POCO中填充它。将[required]放在外键属性而不是导航属性上会更常见。

public class User 
{
public User() 
{
    Subscribers = new List<SubscriberNumber>();
}

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string Username { get; set; }

[Required]
public virtual int BusinessId {get;set;};   // make the foreign key to BusinessNumber required if necessary

[ForeignKey("BusinessId")]
public virtual BusinessNumber BusinessNumber { get; set; }  // this is a nav prop, since it isnt a simple base type

public string BusinessName { get; set; }
public int SubscriberCount { get; set; }

public List<SubscriberNumber> Subscribers { get; set; }
}