0

Apologies if this has already been answered, I cant find an answer to fit my scenario.

I have an entity class and a view model. Sample below :

Entity:

    public class Data
{
    [Key, Column(Order = 0)]
    public int ID { get; set; }

    [Column(Order = 1)]
    public Q1Values Q1 { get; set; }

    [Column(Order = 2)]
    public Q1Values Q2 { get; set; }

}

ViewModel:

    public class DataViewModel
{
    [Key, Column(Order = 0)]
    public int ID { get; set; }

    [Column(Order = 1)]
    public int Q1ID { get; set; }

    [Column(Order = 2)]
    public int Q2ID { get; set; }

    public List<Q1Values> Q1ValuesList {get;set;}

}

Issue I have is that i will have over 50 questions all using the same lookup table 'Q1Values'. The problem with the above is that i will have to manually load/map the FK entitys from the viewmodel to entity model before inserting.

I tried the below with the view model

public class DataViewModel
{
[Key, Column(Order = 0)]
public int ID { get; set; }

[Column(Order = 1)]
public Q1Values Q1ID { get; set; }

[Column(Order = 2)]
public Q1Values Q2ID { get; set; }

public List<Q1Values> Q1ValuesList {get;set;}

}

I then mapped the dropdown like below

@Html.DropDownListFor(m=>m.Q1.ID, new   SelectList(model.Q1Values,"ID","Name"))

But this will still require me to map the to a fully loaded entity in the controller as it will only contain the ID.

What is the best practice for this? Will I need to map the full entity in the controller for each question? Seems long winded as its a lot of duplication.

I tried to define the foreign key manually in my entity class but cannot seem to make it work for multiple FKs. See Below.

public class QOLData
{
    [Key, Column(Order = 0)]
    public int ID { get; set; }

    [Column(Order = 1)]
    public int Q1 { get; set; }

    [Column(Order = 2)]
    public int Q2 { get; set; }

    [ForeignKey("Q1,Q2")]
    public virtual Q1Values Q1Values { get; set; }
}
Robert Kitching
  • 190
  • 1
  • 2
  • 10

1 Answers1

0

Have a look at Defining multiple Foreign Key for the Same table in Entity Framework Code First. I think there are enough information to solve your problem.

Murat Yıldız
  • 11,299
  • 6
  • 63
  • 63