1

给定以下模型:

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; }
}

我将如何Item.Attachments使用 Fluent API 描述导航属性,以便生成的 SQL 正确连接,例如:

SELECT ... FROM Items a 
LEFT JOIN Files b
  ON a.Id = b.ObjectId AND b.ObjectType = 8 (example enum value)

我尝试公开Item.ObjectTypeItem.ObjectId属性,然后在我的项目映射中执行以下操作:

HasMany(x => x.Attachments)
  .WithOptional()
  .Map(x => x.MapKey("ObjectType", "ObjectId"))
  .WillCascadeOnDelete(false);

但这会导致以下运行时错误,可能是因为这不是数据库中的实际外键。

指定的关联外键列“ObjectType、ObjectId”无效。指定的列数必须与主键列数匹配

4

1 回答 1

0

This is not supported in code first mapping because your relation between Item and File is 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.

于 2013-01-13T12:41:47.617 回答