[英]Entity Framework, updating entity exception
I am having following classes: 我正在上以下课程:
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; }
}
And following code in DbContext: 然后在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();
}
When i am trying to update existing entity of LbsNetwork in storage, then i am recieving next exception in Context.Save() method: "System.Data.Entity.Validation.DbEntityValidationException : Propetry: Network, Message: Network is required." 当我尝试更新存储中LbsNetwork的现有实体时,则在Context.Save()方法中收到下一个异常:“ System.Data.Entity.Validation.DbEntityValidationException:Propetry:网络,Message:需要网络。”
I think that there is a problem with one-to-many relations in entities. 我认为实体中的一对多关系存在问题。 I am using next code to update entity:
我正在使用下一个代码更新实体:
public void Update(LbsNetwork network)
{
Context.LbsNetworks.Attach(network);
((DbContext)Context.GetRealization()).Entry(network).State = EntityState.Modified;
Context.Save();
}
I'll be very grateful if you give me my mistakes. 如果您给我我的错误,我将不胜感激。 Thank you.
谢谢。
[InverseProperty("SubNetworks")]
[Required]
public virtual LbsNetwork Network { get; set; }
This cause the problem on your query. 这会导致您的查询出现问题。 I don't think it's a good idea to put a
Required
validation attribute in a navigation property. 我认为将
Required
验证属性放在导航属性中不是一个好主意。 You should put it in a foreign key instead. 您应该将其放在外键中。
[InverseProperty("SubNetworks")]
public virtual LbsNetwork Network { get; set; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.