Lemex
Lemex

Reputation: 3794

Entity Framework Code First Set Mapping

Entity framework code first is setting up my mapping wrong. The mapping issue looks like this:

One user may have a profile

A profile must have one or many standing data values

Standing data values are used across 3/4 different tables and cannot be changed e.g cannot add new column to that table.

The mapping it wants to do looks like:

    public override void Up()
    {
        AddColumn("dbo.StandingDatas", "Person_Id", c => c.Int());
        CreateIndex("dbo.StandingDatas", "Person_Id");
        AddForeignKey("dbo.StandingDatas", "Person_Id", "dbo.People", "Id");
    }

Where as i would prefer the mapping to reside in the People table, this way its easier for the DA to control and report on.

How do I tell enity framework to host my one-to-many relationship on the People table and not the standing data table?

If i change it to a one-to-one from people to standing data this works better.

   public override void Up()
    {
        AddColumn("dbo.People", "Therapies_Id", c => c.Int(nullable: false));
        CreateIndex("dbo.People", "Therapies_Id");
        AddForeignKey("dbo.People", "Therapies_Id", "dbo.StandingDatas", "Id", cascadeDelete: true);
    }

I would prefer something like this but for a one-to-many.

e.g. A command serpated list of Ids within the people table or something better

Thanks

Upvotes: 0

Views: 96

Answers (1)

calebboyd
calebboyd

Reputation: 5753

Its not very clear what your schema is so going off of the description in your first paragraph Your poco's could have the following annotations:

public class User
{
    [Key,ForeignKey("Profile")]
    public int Id { get; set; }
    public Profile Profile { get; set; }
}

public class Profile
{
    [Key]
    public int Id { get; set; }
    public virtual User ProfileOwner { get; set; }
    public virtual ICollection<StandingData> DataCollection { get; set; } 
}

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

    public int ProfileId { get; set; }

    [ForeignKey("ProfileId")]
    public virtual Profile Profile { get; set; }
}

Upvotes: 1

Related Questions