0

I am in a strange situation right now, I have two entities:

public class Proyect
{
    int id;
    List<int> stages;
}

public class Stage
{
    //PK, not FK to proyect
    int id;
}

I know that this is not the best way to model this kind of relation (n->1) but it was done this way and we can't change it.

Does someone know, how do I relate this entities (notation or overriding onModelCreation)?

We are using c#, ET4, VS2012, WS8.

2
  • Is id in Stage a primary key or a foreign key in to Proyect? Commented Nov 19, 2015 at 15:32
  • If that's true, what does the schema in the database actually look like? How is the list of stages in Proyect stored on the database? Commented Nov 19, 2015 at 15:43

1 Answer 1

2

I like to use Data Annotations for simple relationships. You must specify your key field on the Proyect table, and your foreign key on the Stage table. In the Proyect table, you should have a list of Stages, not ints, since you are relating to the Stage object. You can use the virtual keyword to use lazyloading on your related entities.

If you really need a list of type int, containing your stage Ids, just use an unmapped property.

public class Proyect{
    [Key]
    public int id { get; set;}
    public virtual List<Stage> stages { get; set;}
    [NotMapped]
    public virtual List<int> stageIds {
        get {
            return stages == null ? null : stages.Select(t => t.id).ToList();
        }
    }
}

public class Stage{
    public int id { get; set;}
    [ForeignKey("id")]
    public virtual Proyect Proyect { get; set;}
}
Sign up to request clarification or add additional context in comments.

2 Comments

Unfortunately that's going to generate a foreign key in the OP's model and he stated (or at least implied) in his post that they can't change the model (i.e. "it was done this way and we can't change it").
I was under the assumption that the OP can't change the database structure. You can define keys in your entity classes, even if they don't exist in the db.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.