gpt4 book ai didi

c# - Entity Framework 代码优先 : Custom Mapping

转载 作者:行者123 更新时间:2023-11-30 21:13:07 26 4
gpt4 key购买 nike

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

public string Name {get;set}

public ICollection<User> Followers {get;set;}
public ICollection<User> Following {get;set;}
}

我的模型如上所示, Entity Framework 自动创建一个表和 UserUser,在数据库中包含行 User_IDUser_ID1 以映射此模型。我想自己映射该表和行。

我该怎么做,谢谢!!

最佳答案

来自 Scott Gu's blog关于Many-valued Associations :

Many-to-Many Associations The association between Category and Item is a many-to-many association, as can be seen in the above class diagram. a many-to-many association mapping hides the intermediate association table from the application, so you don’t end up with an unwanted entity in your domain model. That said, In a real system, you may not have a many-to-many association since my experience is that there is almost always other information that must be attached to each link between associated instances (such as the date and time when an item was added to a category) and that the best way to represent this information is via an intermediate association class (In EF, you can map the association class as an entity and map two one-to-many associations for either side.).

In a many-to-many relationship, the join table (or link table, as some developers call it) has two columns: the foreign keys of the Category and Item tables. The primary key is a composite of both columns. In EF Code First, many-to-many associations mappings can be customized with a fluent API code like this:

    class ItemConfiguration : EntityTypeConfiguration<Item> {
internal ItemConfiguration()
{
this.HasMany(i => i.Categories)
.WithMany(c => c.Items)
.Map(mc =>
{
mc.MapLeftKey("ItemId");
mc.MapRightKey("CategoryId");
mc.ToTable("ItemCategory");
});
} }

在您的 DbContext 中注册此配置(您使用的 DbContext api 对吗?),如下所示:

  protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);

modelBuilder.Configurations.Add(new ItemConfiguration());
}

祝你好运,希望对你有所帮助!

关于c# - Entity Framework 代码优先 : Custom Mapping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7026342/

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