Given the following model:
public class Item
{
public int Id { get; set; }
public ICollection<File> Attachments { get; set; }
}
public class File
{
public int Id { get; set; }
public ObjectType ObjectType { get; set; } // enum stored as INT
public int ObjectId { get; set; }
}
How would I describe the Item.Attachments navigation property using Fluent API so the resulting SQL joins correctly, such as:
SELECT ... FROM Items a
LEFT JOIN Files b
ON a.Id = b.ObjectId AND b.ObjectType = 8 (example enum value)
I’ve tried exposing Item.ObjectType and Item.ObjectId properties and then doing the following in my Item map:
HasMany(x => x.Attachments)
.WithOptional()
.Map(x => x.MapKey("ObjectType", "ObjectId"))
.WillCascadeOnDelete(false);
But this results in the following runtime error, presumably because this isn’t an actual foreign key in the database.
The specified association foreign key columns ‘ObjectType, ObjectId’
are invalid. The number of columns specified must match the number of
primary key columns
This is not supported in code first mapping because your relation between
ItemandFileis not valid referential constraint. EF code first supports only mappings equivalent to foreign key constraint => columns in foreign key of dependent table must match columns in primary of principal table. Your case expects additional constant column in dependent table.