在实体框架中使用属性映射多对多关系 [英] Mapping a Many-to-Many relationship with an Attribute in Entity Framework

查看:78
本文介绍了在实体框架中使用属性映射多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用Attributes将实体的属性映射到其对应的列.这是一个示例:

I'm always using Attributes to map the properties of my entities to their corresponding columns. Here's an example:

[Table("news_entries")]
public class News
{
    [Key]
    public int Id { get; set; }

    [Column("d_date")]
    public DateTime Date { get; set; }

    [Column("m_text")]
    public string Text { get; set; }

    [Column("id_user")]
    public int UserId { get; set; }

    [ForeignKey("UserId")]
    public User User { get; set; }
}

但是我仍然不知道如何映射表对列名称与属性不匹配的多对多关系.

But I still don't know, how I could map a Many-to-Many relationship, where the table and column names doesn't match with the properties.

我知道我可以在DbContext中使用DbModelBuilder,但是我不想在实体类之外进行映射.是否还可以通过某种方式将这些关系与属性映射?

I know I could use the DbModelBuilder in my DbContext, but I don't want to do the mapping outside of my entity class. Is it somehow possible to map those relationships with Attributes as well?

推荐答案

我知道我可以在DbContext中使用DbModelBuilder,但是我不能 想要在我的实体类之外进行映射.莫名其妙 还能用属性映射那些关系?

I know I could use the DbModelBuilder in my DbContext, but I don't want to do the mapping outside of my entity class. Is it somehow possible to map those relationships with Attributes as well?

不.联结表没有可用于应用属性的类.一旦使用直接多对多映射(联结表隐藏在导航属性后面),就需要使用流畅的API.

No. There is no class for the junction table where you could apply your attributes. Once you use direct many to many mapping (where junction table is hidden behind navigation properties) you need to use fluent API.

也许EF6可以通过自定义约定来实现这一点,但是我最初使用约定处理外键名称的经验并不成功,因此我想联结表将是同样的故事.

Perhaps EF6 will allow this through custom conventions but my initial experience with handling foreign key names with convention wasn't successful so I guess junction table will be the same story.

这篇关于在实体框架中使用属性映射多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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