实体框架4.1代码优先 - 仅使用数据注释来定义多对多 [英] Entity Framework 4.1 Code First - Define many-to-many using data annotations only

查看:94
本文介绍了实体框架4.1代码优先 - 仅使用数据注释来定义多对多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Entity Framework 4.1(Code First方法)中使用Data Annotations定义多对多关系,而不使用模型构建器?



例如,如:

  Product = {Id,Name,...} 
Category = {Id,Name, ...}
ProductCategory = {ProductId,CategoryId}

你得到的照片。 / p>

我不想在上下文中有两个多对一的中间实体 ProductCategory ,因为我没有任何额外的数据,只有两个FK。此外,我应该能够定义中间表的表名,以便与现有数据库一起使用。

解决方案

可以使用默认约定或数据注释定义多对多,但是不可以在没有模型构建器的情况下更改映射到连接表(表的名称和列)。简单的多对多:

  public class Product 
{
public int Id {get;组; }
public virtual ICollection< Category>分类{get;组;
}

public class Category
{
public int Id {get;组; }
public virtual ICollection< Product>产品{get;组;
}

对于使用注释,您可以使用:

  public class Product 
{
[Key]
public int Id {get;组; }
[InverseProperty(Products)]
public virtual ICollection< Category>分类{get;组;
}

public class Category
{
[Key]
public int Id {get;组; }
[InverseProperty(Categories)]
public virtual ICollection< Product>产品{get;组; }
}

如果需要控制连接表到现有数据库的映射, code>模型构建器。数据注释不如流畅的API强大。


Is it possible to define a many-to-many relationship in Entity Framework 4.1 (Code First approach) using Data Annotations only, without model builder?

For example, something like:

Product = { Id, Name, ... }
Category = { Id, Name, ... }
ProductCategory = { ProductId, CategoryId }

You get the picture.

I don't want to have an intermediate entity ProductCategory in the context with two many-to-ones since I don't have any additional data, just the two FKs. Also, I should be able to define table name for the intermediate table for use with an existing database.

解决方案

It is possible to define many-to-many with default conventions or with data annotations but it is not possible to change mapping to junction table (table's name and columns) without model builder. Simple many-to-many:

public class Product
{
    public int Id { get; set; }
    public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    public int Id { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

For using annotations you can use:

public class Product
{
    [Key]
    public int Id { get; set; }
    [InverseProperty("Products")]
    public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    [Key] 
    public int Id { get; set; }
    [InverseProperty("Categories")]
    public virtual ICollection<Product> Products { get; set; }
}

If you need to control mapping of junction table to existing database you need modelBuilder. Data annotations are not as powerful as fluent API.

这篇关于实体框架4.1代码优先 - 仅使用数据注释来定义多对多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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