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:
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."
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. You should put it in a foreign key instead.
[InverseProperty("SubNetworks")]
public virtual LbsNetwork Network { get; set; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.