属性表达式无效.表达式应该代表一个属性 [英] The properties expression is not valid. The expression should represent a property
问题描述
我有这两个实体
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; }
}
Path
定义在 IPathHavingEntity
接口中.
在我的 Seed 方法中,我只想将一首歌曲添加到 Songs
表中,前提是它不存在.出于这个原因,我在添加之前检查专辑路径和歌曲路径组合是否不存在
In my Seed method I want to add a song to the Songs
table only if it doesn't exist. For this reason I check that the album path and song path combination don't exist already before adding it thus
context.Songs.AddOrUpdate(
s => new { FilePath = s.Path, AlbumPath = s.Album.Path },
new Song { TrackNumber = 1, Path = "01 Intro.mp3", Album = one });
问题是我得到了这个错误
The problem is I get this error
属性表达式的=>新 <>f__AnonymousType0``2(FilePath =s.Path, AlbumPath = s.Album.Path)' 无效.表达式应该表示一个属性:C#: 't =>t.MyProperty' VB.Net:'函数(t)t.MyProperty'.指定多个属性时使用匿名类型:C#: 't =>new { t.MyProperty1, t.MyProperty2 }' VB.Net: 'Function(t) New With { t.MyProperty1, t.MyProperty2 }'.
有什么问题?
推荐答案
我今天为一个类似的问题苦苦挣扎了几个小时,终于能够解决它.我不确定这是否适用于您的情况,但值得研究.
I struggled with a similar issue for several hours today and was finally able to resolve it. I'm not sure if this will work for your situation but it's worth investigating.
问题可能是由于您的 Song
实体的 Album
属性被标记为 virtual
.我不是 EF 专家,但我认为它在初始化匿名类型时不喜欢该 virtual
属性.为专辑路径添加一个非虚拟属性(但保留 virtual
导航属性),如下所示:
The problem may be caused by the Album
property of your Song
entity being marked as virtual
. I'm not an EF expert but I don't think it likes that virtual
property when initializing your anonymous type. Add a non-virtual property for the album path (but keep the virtual
navigation property), like this:
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
,如下所示:
And then perform the AddOrUpdate
using that non-virtual property, like this:
context.Songs.AddOrUpdate(
s => new { FilePath = s.Path, AlbumPath = s.AlbumPath },
new Song { TrackNumber = 1, Path = "01 Intro.mp3", Album = one });
EF 应该只允许您添加给定歌曲路径和专辑路径尚不存在的歌曲.您的 Song
域对象是否可以具有非虚拟 AlbumPath
属性是另一个问题,但这至少应该允许您以您描述的方式运行种子方法.
EF should then only allow you to add songs where the given song path and album path do not already exist. Whether your Song
domain object can have a non-virtual AlbumPath
property is another question but this should at least allow you to run your seed method in the way you described.
这篇关于属性表达式无效.表达式应该代表一个属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!