0

I have a join table with an additional field relevant to the join:

VirtualDatastreamId  INT  NOT NULL
DatastreamId         INT  NOT NULL
FormulaElement       INT  NOT NULL

All columns are the primary key.

The POCO this is mapped to is:

public class VirtualDatastreamMap 
{
    public virtual Datastream Datastream { get; set; }
    public virtual VirtualDatastream VirtualDatastream { get; set; }
    public virtual string FormulaElement { get; set; }
}

I do not have foreign key properties in the model as, to me, the concept of a foreign key is an implementation detail and should be encapsulated by the relationships specified by the class. I'd prefer not to add these if possible.

How do I map this with Fluent API? I was hoping for something like the below (which unfortunately doesn't work):

modelBuilder.Entity<VirtualDatastreamMap>()
            .HasKey(vdm => 
                new 
                { 
                    DatastreamId = vdm.Datastream.Id, 
                    VirtualDatastreamId = vdm.VirtualDatastream.Id, 
                    FormulaElement = vdm.FormulaElement 
                });

The field names of the anonymous type have to be named as an object cannot have two fields with the same name.

I see from this question that this issue was raised in the answer but there doesn't seem to be anything further.

If it's not possible, which is a better option?

  1. Add the foreign key properties to the model
  2. Add an Id field to the database and the model

Thanks

Community
  • 1
  • 1
Daniel
  • 452
  • 3
  • 12

1 Answers1

1

Each column of the composite primary key has to be mapped to a scalar property in the entity. Your ideal solution will not work.

In Option 2 you would have to create a unique key also and check for unique key violations. EF does not have built in support for unique keys. Hence I would pick option 1.

Eranga
  • 32,181
  • 5
  • 97
  • 96