首先是实体框架代码。如何将对象类型文件的列表添加到已具有该类型属性的对象

问题描述 投票:0回答:2

有一个对象期刊。期刊有公司领域。

[Required]
[Display(Name = "Company")]
public int CompanyID { get; set; }

[ForeignKey("CompanyID")]
public Company Company { get; set; }

公司有一份期刊清单

  public IList<Journal> Journals { get; set; }

项目上线几个月后,就要求期刊有可能让多家公司分配给它。

简单的解决方案是将对象字段更改为:

 public IList<Company> Companies { get; set; }

在期刊和公司之间的多对多表格中进行了映射,但正如开头所述,项目和数据库正在生产中。我看到的唯一解决方案是在公司字段顶部添加公司(多公司)字段列表。

不知道如何在实体中使用它。

c# entity-framework ef-code-first
2个回答
0
投票

您可以尝试使用映射表来解决此问题,以规范化您的新需求,从而使两个表之间的关系变为M:M。下面是它在EF中的外观示例。

    public class Company
    {
        [Key]
        public int Id { get; set; }

        public virtual ICollection<CompanyJournals> CompanyJournals { get; set; }
    }

    public class Journal
    {
        [Key]
        public int Id { get; set; }

        public virtual ICollection<CompanyJournals> CompanyJournals { get; set; }
    }

    public class CompanyJournals
    {
        [Key]
        public int Id { get; set; }

        public int CompanyId { get; set; }

        public int JournalId { get; set; }

        [ForeignKey("CompanyId")]
        public virtual Company Company { get; set; }

        [ForeignKey("JournalId")]
        public virtual Journal Journal { get; set; }
    }

0
投票

原来的情况: - 公司 - 期刊是一对多的关系。 - 每家公司都有零个或多个期刊, - 每个期刊都属于一个公司

期望的情况: - 公司 - 期刊是多对多的关系 - 每个公司都有零个或多个期刊 - 每个期刊都有零个或多个公司。

通常使用联结表来完成多对多关系。在实体框架类中,您不需要此联结表。在您的查询中,您将使用ICollections:

class Company
{
    public int Id {get; set;}   // primary key

    // every Company has zero or more Journals
    public virtual ICollection<Journal> Journals {get; set;}

    ... // other properties
}
class Journal
{
    public int Id {get; set;}   // primary key

    // every Journal is used by zero or more Companies
    public virtual ICollection<Company> Companies{get; set;}

    ... // other properties
}

如果要更改现有实体框架配置数据库的配置,则需要实现迁移。 See Entity Framework Code First Migrations

您在迁移中需要做的事情:

(1)创建联结表Company_Journals 两个领域: (a)int CompanyId,required,公司的外键 (b)int JournalId,必填,期刊的外键

这两个字段的组合将是主键,请参阅CreateTable

class AddCompanyJournalsTable: DbMigration
{
    public override void Up()
    {
        CreateTable("dbo.Company_Journals",
        c => new
        {
            CompanyId = c.Int(nullable: false, identity: true)
            JournalId = c.Int(nullable: false, identity: true)
        });

CreateTable的返回值是TableBuilder object,可用于定义主键和外键

.PrimaryKey(t => new {t.CompanyId, t.JournalId})
.ForeignKey("dbo.Companies", t => t.CompanyId, cascadeDelete: false)
.ForeignKey("dbo.Journals", t => t.JournalId, cascadeDelete: false)

(2)对于您在先前版本中拥有的每个期刊,创建一个指向公司和期刊的Company_Journal:

IQueryable<Journal> allJournals = ...
foreach (Journal journal in allJournals)
{
    dbContext.Journals.Add(new Journal()
    {
        JournalId = journal.Id, // or whatever primary key you have in Journal
        CompanyId = journal.CompanyId
    });
}

(3)使用DropColumn删除Journal.CompanyId

© www.soinside.com 2019 - 2024. All rights reserved.