Reputation: 63
I have a class that has a composite key defined as a seperate class.
public class ClassA : Entity
{
public virtual ClassACompositeKey CompositeKey { get; set; }
}
public class ClassACompositeKey
{
public int ThisId { get; set; }
public int ThatId { get; set; }
public int OtherId { get; set; }
}
Having some difficulty mapping this using fluent api for entity framework. I have tried creating a complex type configuration for the composite class with no luck. When I attempt the mapping as
this.HasKey(k => new { k.CompositeKey.ThisId, k.CompositeKey.ThatId, k.CompositeKey.OtherId });
I get an error stating that
The properties expression 'k => new <>f__AnonymousType2 (ThisId = k.CompositeKey.ThisId, ThatId = k.CompositeKey.ThatId, OtherId = k.CompositeKey.OtherId)' is not valid. The expression should represent a property.
I'm somewhat new to EF and Fluent API so I don't even know if this is going to be possible. Any help would be appreciated.
Upvotes: 2
Views: 500
Reputation: 177133
Unfortunately it's not supported. Key properties must have primitive types (int
, long
, string
, Guid
, DateTime
, etc.) and be directly inside the entity class without a wrapping class around them. So you must define a composite key like so:
public class ClassA : Entity
{
public int ThisId { get; set; }
public int ThatId { get; set; }
public int OtherId { get; set; }
}
... with the Fluent mapping:
this.HasKey(k => new { k.ThisId, k.ThatId, k.OtherId });
Upvotes: 3