gpt4 book ai didi

c# - Code First - 自引用一对多关系

转载 作者:太空狗 更新时间:2023-10-29 21:45:49 25 4
gpt4 key购买 nike

我在这里发现了很多类似的问题,但似乎没有一个能帮助我解决问题。流利的 api 和属性没有帮助。数据库已创建,但在向其中添加对象时,它崩溃了。我想要一个包含自身集合的类。这是我的代码:

[Table("UObjects")]
public class UObject
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Browsable(false)]
public long ID { get; set; }
public string Name { get; set; }
[Browsable(false)]
public long? ParentID { get; set; }

public virtual UObject UParent { get; set; }
[Browsable(false)]
public virtual ICollection<UObject> UObjects { get; set; }
}


public class MyContext : DbContext
{
public DbSet<UObject> UObjects { get; set; }

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// This fluent API didn't help
//modelBuilder.Entity<UObject>()
// .HasOptional(u => u.UParent)
// .WithMany(u => u.UObjects)
// .HasForeignKey(u => u.ParentID);

//modelBuilder.Entity<UObject>()
// .HasOptional(u => u.UParent)
// .WithMany(u => u.UObjects)
// .Map(c =>
// {
// c.MapKey("ParentID");
// c.ToTable("UObjects");
// });
}
}

数据库中的记录是这样的:

ID | Name       | ParentID
------------------------------------
1 | First | 0
2 | SubFirst | 1
3 | SubSecond | 1
4 | SubThird | 2
5 | SubFourth | 2

接下来我的对象应该如何加载实体:

   - First
- SubFirst
- SubThird
- SubFourth
- SubSecond

但是每个对象都有一个空集合。我应该怎么做才能使其正常工作?

最佳答案

您只需要通过更正字段而不是像这样导航属性来提及自引用:

 [ForeignKey("UParent")]    // EF need for self reference
public long? ParentID { get; set; }

然后在构造函数中,像这样初始化导航属性:

  public UObject()       
{
// this is necessary otherwise EF will throw null object reference error. You could also put ?? operator check for a more interactive solution.
UObjects = new List<UObject>();
}

并且还需要像您一样覆盖,但像这样:

   protected override void OnModelCreating(DbModelBuilder modelBuilder)     
{
// folowwing is also necessary in case you're using identity model
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<UObjects>()
.HasOptional<UObjects>(u => u.UParent) // EF'll load Parent if any
.WithMany(u => u.UObjects); // load all childs if any
}

关于c# - Code First - 自引用一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12989566/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com