2013-11-23 47 views
7

我有這兩個實體屬性表達式無效。表達應代表屬性

public class Song : IPathHavingEntity 
    { 
     public int Id { get; set; } 
     [Required] 
     public string Path { get; set; } 
     [Required] 
     public virtual Album Album { get; set; } 
     [Required] 
     public int TrackNumber { get; set; } 
    } 

public class Album : IPathHavingEntity 
    { 
     public int Id { get; set; } 
     [Required] 
     public string Path { get; set; } 
     public virtual IEnumerable<Song> Songs { get; set; } 
     [Required] 
     public int AlbumNumber { get; set; } 
    } 

PathIPathHavingEntity接口定義。

在我的Seed方法中,我只想爲Songs表添加一首歌曲,但前提是它不存在。出於這個原因,我檢查專輯路徑和歌路組合並不因此增加它

context.Songs.AddOrUpdate(
    s => new { FilePath = s.Path, AlbumPath = s.Album.Path }, 
    new Song { TrackNumber = 1, Path = "01 Intro.mp3", Album = one }); 

問題之前就已經存在,則出現此錯誤

The properties expression 's => new <>f__AnonymousType0``2(FilePath = s.Path, AlbumPath = s.Album.Path)' is not valid. The expression should represent a property: C#: 't => t.MyProperty' VB.Net: 'Function(t) t.MyProperty'. When specifying multiple properties use an anonymous type: C#: 't => new { t.MyProperty1, t.MyProperty2 }' VB.Net: 'Function(t) New With { t.MyProperty1, t.MyProperty2 }'.

什麼問題?

回答

4

我今天在幾個小時內也遇到過類似的問題,終於能夠解決它。我不確定這是否適合您的情況,但值得調查。

問題可能是由Song實體的Album屬性標記爲virtual引起的。我不是EF專家,但我不認爲它在初始化您的匿名類型時喜歡virtual屬性。添加專輯路徑的非虛擬財產(但保留virtual導航屬性),就像這樣:

public class Song : IPathHavingEntity 
{ 
    public int Id { get; set; } 

    [Required] 
    public string Path { get; set; } 

    [Required] 
    public virtual Album Album { get; set; } 

    public string AlbumPath { get; set; } 

    [Required] 
    public int TrackNumber { get; set; } 
} 

,然後使用非虛擬財產進行AddOrUpdate,就像這樣:

context.Songs.AddOrUpdate(
    s => new { FilePath = s.Path, AlbumPath = s.AlbumPath }, 
    new Song { TrackNumber = 1, Path = "01 Intro.mp3", Album = one }); 

EF應該只允許您添加歌曲,而歌曲路徑和專輯路徑尚不存在。 Song域對象是否可以具有非虛擬AlbumPath屬性是另一個問題,但這應該至少允許您按照所描述的方式運行種子方法。

0

在我的情況下,更改映射器中的以下值工作。

來自: this.HasKey(t => new {FirstName = t.FirstName,LastName = t.LastName});

收件人: this.HasKey(t => new {t.FirstName,t.LastName});

3

以我爲例,我這樣做,對模型類中唯一的修改忘記把{get; set;}與財產申報,因此...它解決了我的問題。

像這樣:

前:

public int Supplier_ID; 
public String Supplier_Code; 

後:

public int Supplier_ID { get; set; } 
public String Supplier_Code { get; set; } 

請檢查你的模型類應該有Get/Set財產