我正在上课:
public class LbsNetwork : BaseEntity
{
public virtual Guid Uuid { get; set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
[InverseProperty("Network")]
public virtual ICollection<LbsSubNetwork> SubNetworks { get; set; }
}
public class LbsSubNetwork:BaseEntity
{
public virtual int ForeignId { get; set; }
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual int Major { get; set; }
[InverseProperty("SubNetworks")]
[Required]
public virtual LbsNetwork Network { get; set; }
[InverseProperty("SubNetwork")]
public virtual ICollection<LbsDevice> Devices { get; set; }
}
public class LbsDevice:BaseEntity
{
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual int Minor { get; set; }
public virtual int ForeignId { get; set; }
[InverseProperty("Devices")]
[Required]
public virtual LbsSubNetwork SubNetwork { get; set; }
public virtual BeaconProximity Proximity { get; set; }
}
关注DbContext中的代码:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<LbsNetwork>().ToTable("LbsNetworks");
modelBuilder.Entity<LbsNetwork>().HasMany<LbsSubNetwork>(x=>x.SubNetworks)
.WithRequired(x=>x.Network).HasForeignKey(x=>x.ForeignId).WillCascadeOnDelete();
modelBuilder.Entity<LbsSubNetwork>().HasMany<LbsDevice>(x=>x.Devices)
.WithRequired(x=>x.SubNetwork).HasForeignKey(x=>x.ForeignId).WillCascadeOnDelete();
}
当我尝试在存储中更新LbsNetwork的现有实体时,我接收到Context.Save()方法中的下一个异常: &#34; System.Data.Entity.Validation.DbEntityValidationException:Propetry:网络,消息:网络是必需的。&#34;
我认为实体中的一对多关系存在问题。我正在使用下一个代码来更新实体:
public void Update(LbsNetwork network)
{
Context.LbsNetworks.Attach(network);
((DbContext)Context.GetRealization()).Entry(network).State = EntityState.Modified;
Context.Save();
}
如果你把我的错误告诉我,我将非常感激。谢谢。
答案 0 :(得分:0)
[InverseProperty("SubNetworks")]
[Required]
public virtual LbsNetwork Network { get; set; }
这会导致查询出现问题。我不认为在导航属性中放置Required
验证属性是个好主意。你应该把它放在外键中。
[InverseProperty("SubNetworks")]
public virtual LbsNetwork Network { get; set; }