gpt4 book ai didi

c# - 1 到 ef5 中与自身的多关系?

转载 作者:太空宇宙 更新时间:2023-11-03 19:10:56 24 4
gpt4 key购买 nike

我有这些类(class):

public class ContentType
{
public int ContentTypeId{get;set;}
public string Name{get;set;}
public int Lang{get;set;}
public bool IsPublished{get;set;}
public int? ParentId { get; set; }
public int UserId { get; set; }
public virtual User User { get; set; }
}

public class Context : DbContext
{
public Context()
{
base.Configuration.LazyLoadingEnabled = false;
base.Configuration.ProxyCreationEnabled = false;
base.Configuration.ValidateOnSaveEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
public DbSet<ContentType> ContentTypes { get; set; }
}

现在每个内容类型都有一个父类和一个子类列表。如何使用 ef5 在模型和上下文中定义它?

最佳答案

如果你想让你的contenttype类有 child 使用这个代码:

public class ContentType
{
///other properties
public ContentType Parent { get; set; }
public int? ParentId { get; set; }
public ICollection<ContentType> Childern { get; set; }
}

然后这样映射:

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ContentType>()
.HasMany(c => c.Children)
.WithOptional(c => c.Parent)
.HasForeignKey(c => c.ParentId);

base.OnModelCreating(modelBuilder);

}

你去..

关于c# - 1 到 ef5 中与自身的多关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20727947/

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