简体   繁体   中英

ASP.Net Entity Framework one-to-many relationship: How to establish dependency and lazy loading not working

I have two classes. The class BC_Instance can have many BC_InstanceSession and a BC_InstanceSession is dependent on a BC_Instance and should be deleted when it's relative BC_Instance is deleted.

//Instance
public class BC_Instance
{
    public int ID { get; set; }
    //sessions
    public ICollection<BC_InstanceSession> sessions { get; set; }
}

//Instance session
public class BC_InstanceSession
{
    [Key]
    public int ID { get; set; }
    [ForeignKey("Instance")]
    public int InstanceID { get; set; }
    public virtual BC_Instance Instance { get; set; }
}

I have detected a few problems with this configuration. First Sessions are not deleted when it's Instance is deleted. Is it possible to specify that a session cannot exist without an instance or I need to manually delete them?

Second there seems to be a problem in the mapping to the database. A Session has two foreign keys on the Database InstanceID and BC_Instance_ID as show in the image below: 在此处输入图片说明

Finally Lazy loading does not work. Explicit loading is needed to access the Sessions for an instance (code below)

BC_Instance instance = db.BiocloudInstances.Include(i => i.sessions).Where(i => i.ID == id).First();

For the first question you can use a CascadeOnDelete , something like:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
   modelBuilder.Entity<BC_Instance>()
               .HasMany(i => i.sessions) 
               .WithRequired(s => s.Instance) 
               .WillCascadeOnDelete(true);
   }

For the second one, if you look on the EntityFramework documentation they specify that a 1-n relationship is used without the ForeignKey adnotation. So, because you declare your relationship virtual, EF will add 2 keys. To fix this, remove the ForeignKey adnotation and the public int InstanceID { get; set; } public int InstanceID { get; set; } public int InstanceID { get; set; } row. (More on their page here )

Third , as i specified in the comment,
the lazy loading is not working because you didn't specify virtual to your ICollection . Like: public virtual ICollection<BC_InstanceSession> sessions { get; set; } public virtual ICollection<BC_InstanceSession> sessions { 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM