简体   繁体   English

分配 Id 后实体框架导航属性为空

[英]Entity Framework navigation properties is empty after assigned Id

I have the following我有以下

public class MainClass {
    public int Id  { get;set; }

    public virtual ICollection<SubClass> SubClasses { get;set; }
}

public class SubClass {
    public int MainClassId  { get;set; }

    public virtual MainClass MainClass { get;set; }
}

and i have setup mapping for one to many.我已经设置了一对多的映射。 The problem i have is when i do this :我遇到的问题是当我这样做时:

var subClass = new SubClass();
subClass.MainClassId = 1;
_dbset.SaveChanges(subClass);

//subClass.MainClass is null after save

i will need to call my get function with id=1 only i can get the MainClass entity.我将需要使用 id=1 调用我的 get 函数,只有我才能获得 MainClass 实体。 Anyone has any idea whats the issue causing this?任何人都知道导致此问题的原因是什么?

You should add subClass to the mainClass's collection of SubClasses and then save changes.您应该将subClass添加到mainClass's SubClasses集合中,然后保存更改。

So like,所以喜欢,

var mainClass = _dbset.MainClasses.Single(x => x.id == mainClassId); 
var subClass = new SubClass();
//populate subClass without setting mainclassId.
mainClass.SubClasses.Add(subClass);
_dbset.SaveChanges();

The following would work:以下将起作用:

public class MainClass {
    public int Id  { get;set; }

    public virtual  ICollection<SubClass> SubClasses { get;set; }
}

public class SubClass {
    public int Id  { get;set; }
    [ForeignKey("MainClass")]
    public int MainClassId  { get;set; }

    public virtual MainClass MainClass { get;set; }
}

If you used code-first approach, you might be missing modelbuilder for 1:M relationship.如果您使用代码优先的方法,您可能会缺少 1:M 关系的模型构建器。 In your Context in method OnModelCreating you need to have something like this.在 OnModelCreating 方法中的 Context 中,您需要有这样的东西。

modelBuilder.Entity<MainClass>()
      .HasMany(e => e.SubClass)
      .WithRequired(e => e.MainClass)
      .WillCascadeOnDelete();

Next thing that comes to my mind is that you might want to use include in your get method to specify that you need to load all subclasses for main class我想到的下一件事是您可能希望在 get 方法中使用 include 来指定您需要为主类加载所有子类

 context.MainClass.Include(x => x.SubClass).ToList();

or use some other method to load joined data.或使用其他方法加载连接的数据。 Link 关联

I hope that will help you.我希望这会帮助你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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