简体   繁体   English

实体框架代码优先中基于条件的关系

[英]Relationship on the basis of Condition in Entity Framework Code First

I need to create relationship between three entity Party -- Organization Party -- Person 我需要在三个实体Party - Organization Party - Person之间建立关系

But at a one time Party will be organization or Person like below. 但是一次,聚会将是下面的组织或人。

conditionalRelations: {    
    PartyTypeCode: {
        "1": { entity: "Person" },
        "2": { entity: "Organization" }
      }
}

If party type is 1 then relation will be Party ->Person . 如果party type为1,则关联将为Party ->Person
If party type is 2 then relation will be Party-> Organization . 如果方类型为2,则关系将为方Party-> Organization

I need to Configure this relation in ASP.NET MVC4 scaffolding .(Entity Framework Code First) 我需要在ASP.NET MVC4 scaffolding配置此关系。(实体框架代码优先)

It's been a while since I did EF Code First, but I believe this should (more or less) do the trick (given that it's a new database you want to make): 自从我执行EF Code First以来已经有一段时间了,但是我相信这应该(或多或少)能够成功(因为这是您要创建的新数据库):

abstract class Party {
    int Field1 {get;set;}
    int Field2 {get;set;}

    virtual ICollection<PartyType1Party> Parties {get;}
}

class Person {
    string Name {get;set;}
    int Age {get;set;}
}

class OrganizationParty {
    int Something {get;set;}
    int OtherThing {get;set;}

    virtual ICollection<PartyType2Party> Parties {get;}
}

class PartyType1Party : Party {
    Person OrganizerOrSomeRandomPropertyName {get;set;}
}

class PartyType2Party : Party {
    OrganizationPart Organization {get;set;}
}

class Context : DbContext {
    DbSet<Party> Parties {get;set;}
    DbSet<Person> Persons {get;set;}
    DbSet<OrganizationParty> OrganizationParties {get;set;}
}

Instead of manually tracking which parties are type 1 and type 2, you let EF deal with this for you (by way of which class you are dealing with). 与其手动跟踪类型1和类型2的各方,不如让EF为您处理(通过您所处理的类)。 If you already have an existing database and need to follow it's scheem, then I don't know how to resolve it (though I did something like that a while back, I can't recall how). 如果您已经有一个现有数据库并且需要遵循它的原则,那么我不知道如何解决它(尽管我前一段时间做了类似的事情,但我不记得如何)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM