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

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

问题描述

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

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

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

但是,EF 约定会将数据库表创建为:

However the EF conventions will create the DB tables as:

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

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

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

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

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

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