EF5 Fluent API映射

时间:2012-12-13 15:26:49

标签: c# entity-framework asp.net-mvc-4 linq-to-entities entity-relationship

我正在尝试映射这些实体:

 [Table("AAN_DigitalLib_Asset")]
    public class Asset
    {
    [Column("ID")]
    public int ID { get; set; }

    [Column("format_id")]
    public int FormatID { get; set; }

    [Column("person_id")]
    public int? PersonID { get; set; }

    [Column("publicationYear")]
    public int? PublicationYear { get; set; }

    public Person People { get; set; }

    //public virtual AssetKeyword AssetKeywords { get; set; }

    public virtual ICollection<AssetKeyword> AssetKeywords { get; set; }
}

使用这些实体:

[Table("AAN_DigitalLib_AssetKeyword")]
    public class AssetKeyword
    {
        [Column("ID")]
        public int ID { get; set; }

        [Column("asset_id")]
        public int AssetID { get; set; }

        [Column("keyword")]
        public string Keyword { get; set; }
    }

单个Asset可以有多个AssetKeywords。数据库中没有指定关系,因此如何使用Fluent API创建一个?

1 个答案:

答案 0 :(得分:1)

添加

[ForeignKey("AssetID")]
public virtual Asset Asset { get; set; }
你的AssetKeyword类上的

修复它吗?

如果没有,请在onModelCreating()

中执行此操作
modelBuilder.Entity<AssetKeyword>()
                    .HasRequired(p => p.Asset)
                    .WithMany()
                    .HasForeignKey(p => p.AssetID);