Search code examples
c#vb.nettheoryentity-framework-5

How would I defined a 1-1 relationship using EF-5 code-first


How would I define a set of POCO classes for Entity Framework 5 with the following relationships:

Primary has a 1-1 relationship with Secondary.Data, and also Primary has a 1-1 relationship with Tertiary.Data

        ---------(1)- Secondary.Data
Primary +
        ---------(1)- Tertiary.Data

So that Primary has an auto-number (IDENTITY in sql server) Primary Key (Primary.PrimaryID) and each of the child classes primary keys are also the foreign key to Primary (eg. Secondary.Data.PrimaryID is both primary key as well as the foreign key to Primary.PrimaryID)

Edit

Secondary and Tertiary represent Schemas in SQL Server and are represented in code by namespaces.


Solution

  • In the Primary class as follows:

        [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int PrimaryID { get; set; }
    
        public virtual Secondary SecondaryEntity { get; set; }
        public virtual Tertiary TertiaryEntity { get; set; }
    

    In each of the other two classes you would do this for the ID:

        [Key, ForeignKey("PrimaryEntity")]
        public int PrimaryID { get; set; }
    
        public virtual Primary PrimaryEntity { get; set; }
    

    The ForeignKey attribute needs to point to the name of the virtual property that you have on the object, in this case PrimaryEntity.

    I hope this helps.

    EDIT: Per Ladislav's answer to this question, and per what we discussed in Chat, you'll need to make sure that your Secondary and Tertiary classes, though in separate namespaces and schemas, have different class names.