如何使用实体框架流畅的API来配置多对多的关系 [英] How to configure many to many relationship using entity framework fluent API

查看:140
本文介绍了如何使用实体框架流畅的API来配置多对多的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

类帐户
{
public int Id {get;组; }
public string Name {get;组; }
public virtual ICollection< Product>产品{get;组;
}

一个帐户可以有多个产品。 / p>

然而,EF约定将创建数据库表:

 产品表
--------------
Id
名称
Account_Id< - 这是什么?

帐户表
--------------
Id
名称
/ pre>

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

  AccountProducts Table 
- -------------------
Account_Id
Product_Id


解决方案

  modelBuilder.Entity< Account>()
.HasMany(a => a.Products)
.WithMany()
.Map(x =>
{
x.MapLeftKey(Account_Id);
x.MapRightKey(Product_Id);
x.ToTable(AccountProducts);
});


I'm trying to set up a many to many relationship in EF code first but the default conventions is getting it wrong. The following classes describes the relationship:

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; }
}

One Account can have many Products.

However the EF conventions will create the DB tables as:

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

Accounts Table
--------------
Id
Name

This doesn't look like a many-to-many table structure? How can i get configure the fluent API to reflect the relationship and create an intermediary table:

AccountProducts Table
---------------------
Account_Id
Product_Id

解决方案

modelBuilder.Entity<Account>()
            .HasMany(a => a.Products)
            .WithMany()
            .Map(x =>
            {
                x.MapLeftKey("Account_Id");
                x.MapRightKey("Product_Id");
                x.ToTable("AccountProducts");
            });

这篇关于如何使用实体框架流畅的API来配置多对多的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆