Mapping a Many-to-Many relationship with an Attribute in Entity Framework

一个人想着一个人 提交于 2019-12-23 18:35:53

问题


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.

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?


回答1:


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?

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.

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.



来源:https://stackoverflow.com/questions/16505755/mapping-a-many-to-many-relationship-with-an-attribute-in-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!