本文介绍了我怎么名称EF6一个多对多的表,我需要添加特殊的映射呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用EF 6和试图映射一个多对多的关系。到目前为止,我有:

 公共部分类ObjectiveDetail
{
    公共ObjectiveDetail()
    {
        this.SubTopics =新的List<&子话题GT;();
    }
    公众诠释ObjectiveDetailId {搞定;组; }
    公共字符串文本{搞定;组; }
    公共虚拟的ICollection<&子话题GT;子专题{搞定;组; }
}公共部分类子话题
{
    公共子话题()
    {
        this.ObjectiveDetails =新的List< ObjectiveDetail>();
    }
    公众诠释SubTopicId {搞定;组; }
    公众诠释号码{搞定;组; }
    公共字符串名称{;组; }
    公共虚拟的ICollection< ObjectiveDetail> ObjectiveDetails {搞定;组; }
}

我们的DBA将会在code为众多写了许多表。如果这是如下
与表名 ObjectiveDetailSubTopic 或完全不同的东西?

  CREATE TABLE [DBO]。[ObjectiveDetailSubTopic](
    [ObjectiveDetailId] INT NOT NULL,
    [SubTopicId] INT NOT NULL
);

谁能告诉我,如果这是创建该表的正确方法。另外我必须
添加一些code到ObjectiveDetail和子话题类映射到新加入的类等等
EF会知道该怎么办?


解决方案

As long as you follow the SQL Database table naming conventions, the table name can be anything. I usually name the join table like yours, by connecting the two table names.

To create the join table using sql, see below:

 CREATE TABLE [dbo].[ObjectiveDetailSubTopic](
        ObjectiveDetailSubTopicId int identity primary key,
        ObjectiveDetailId INT NOT NULL,
        SubTopicId  INT NOT NULL,
        foreign key(ObjectiveDetailId) references ObjectiveDetail(ObjectiveDetailId ),
        foreign key(SubTopicId) references SubTopic(SubTopicId )
    );

But you don't need to create the join table by your own, Entity Framework will create it for you. You just need to mapping the relationship with the Fluent API in your DbContext class like below:

   protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ObjectiveDetail>().
            HasMany(c => c.SubTopics).
            WithMany(p => p.ObjectiveDetails).
            Map(m =>
                    {
                        m.MapLeftKey("ObjectiveDetailId ");
                        m.MapRightKey("SubTopicId ");
                        m.ToTable("ObjectiveDetailSubTopic");
                    });
    }

这篇关于我怎么名称EF6一个多对多的表,我需要添加特殊的映射呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 00:34