简体   繁体   中英

Relationship on the basis of Condition in Entity Framework Code First

I need to create relationship between three entity 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 .
If party type is 2 then relation will be Party-> Organization .

I need to Configure this relation in ASP.NET MVC4 scaffolding .(Entity Framework Code First)

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):

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). 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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