相关疑难解决方法(0)

如何使用实体框架流畅的API配置多对多关系

我试图首先在EF代码中建立多对多关系,但默认约定是错误的.以下类描述了这种关系:

class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
}

class Account
{        
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

一个帐户可以有许多产品.

但是,EF约定将创建DB表,如下所示:

Products Table
--------------
Id
Name
Account_Id  <- What is this?

Accounts Table
--------------
Id
Name
Run Code Online (Sandbox Code Playgroud)

这看起来不像是一个多对多的表结构?如何配置流畅的API以反映关系并创建中间表:

AccountProducts Table
---------------------
Account_Id
Product_Id
Run Code Online (Sandbox Code Playgroud)

c# associations ef-code-first entity-framework-4.1

25
推荐指数
2
解决办法
3万
查看次数

EF Core 5.0 中的多对多关系是否可以配置为仅保留一个导航属性(在一侧)?

我已经使用以下代码配置了我的 DbContext(EF Core 5.0):

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>()
        .HasMany(p => p.Roles)
        .WithMany(p => p.Users)
        .UsingEntity<Dictionary<string, object>>("UsersToRoles",
            x => x.HasOne<Role>().WithMany().HasForeignKey("UserId"),
            x => x.HasOne<User>().WithMany().HasForeignKey("UserId"),
            x => x.ToTable("UsersToRoles"));

    modelBuilder.Entity<Role>()
        .ToTable("Roles")
        .Property(r => r.Application)
        .IsRequired();

    base.OnModelCreating(modelBuilder);
}
Run Code Online (Sandbox Code Playgroud)

问题是我不希望Role实体持有Users. 我保留它是因为 EF Core 需要它来配置多对多关系。

有没有办法创建相同的关系,但不必定义Role.Users导航属性?

.net c# many-to-many navigation-properties entity-framework-core

3
推荐指数
1
解决办法
121
查看次数