本文介绍了如何使用实体框架流畅API来配置多对多的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想建立一个许多人在EF code第一,但默认的公约是得到了错误的一对多关系。下面的类描述的关系:
类产品
{
公众诠释标识{搞定;组; }
公共字符串名称{;组; }
}类账户
{
公众诠释标识{搞定;组; }
公共字符串名称{;组; }
公共虚拟的ICollection<产品与GT;产品{搞定;组; }
}
一个账户可以有很多的产品。
然而,EF约定将创建数据库表如下:
产品表
--------------
ID
名称
ACCOUNT_ID< - 这是什么?账户表
--------------
ID
名称
这看起来并不像一个多到多表结构?我怎样才能配置流利的API,以反映的关系,并创建一个中介表:
AccountProducts表
---------------------
帐户ID
PRODUCT_ID
解决方案
modelBuilder.Entity<&帐户GT;()
.HasMany(一个= GT; 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");
});
But that is called many-to-many relationship, not one-to-many.
这篇关于如何使用实体框架流畅API来配置多对多的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!