0

我想這些實體映射:EF5流利的API映射

[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

請問您AssetKeyword類中添加

[ForeignKey("AssetID")] 
public virtual Asset Asset { get; set; } 

解決這個問題?

如果不這樣做,那麼這樣做在你的onModelCreating()

modelBuilder.Entity<AssetKeyword>() 
        .HasRequired(p => p.Asset) 
        .WithMany() 
        .HasForeignKey(p => p.AssetID); 
+0

謝謝你,我想你的第一個例子做的伎倆。 – user547794