我将一些复杂的JSON直接加载到模型类中,但我想确保如果删除根记录,则子记录也将被删除。
但是,由于我使用的是ComplexType,因此我似乎无法正确理解语法。
非常大的JSON片段的其余部分都可以正常工作,但是下面的简化示例所代表的部分却无效。
示例事件JSON:
{"eventId":12345,
"zone": {
"beach": {
"score": 19,
"team": [{
"id": "abcdef",
"name": "Barry",
"playerType": 2
},
{
"id": "bvfe43",
"name": "Adam",
"playerType": 1
},
{
"id": "g3yh6",
"name": "Mary",
"playerType": 1
}]
},
"cave": {
"score": 1,
"team": [{
"id": "qPoavMkCTeKIy_htsvSKpQ",
"name": "CAPITALMONCALAMARICRUISER",
"playerType": 3
},
{
"id": "ggsd84",
"name": "Tibor",
"playerType": 1
},
{
"id": "2332edc",
"name": "Jun",
"playerType": 1
},
{
"id": "f234fg54",
"name": "Aaron",
"playerType": 1
}]
}
}
每个事件都有一个zone.beach和zone.cave,并且zone.beach和zone.cave都有一个得分和一个团队。
我的ef模型是:
public class Event
{
[Key]
public int id { get; set; }
public int eventId { get; set;}
public Zone zone { get; set;}
}
[ComplexType]
public class Zone
{
public Beach beach { get; set; }
public Cave cave { get; set; }
}
[ComplexType]
public class Beach
{
public int score { get; set; }
public ICollection<Team> team { get; set; }
}
[ComplexType]
public class Cave
{
public int score { get; set; }
public ICollection<Team> team { get; set; }
}
public class Team
{
[Key]
public int teamId { get; set;}
public string id { get; set;}
public string name { get; set;}
public int playerType { get; set;}
}
我这样加载json:
var event = JsonConvert.DeserializeObject<Event>(content);
但是当按数据库使用以下代码初始化时:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Event>()
.HasMany(a => a.zone.beach.team)
.WithRequired()
.WillCascadeOnDelete(true);
modelBuilder.Entity<Event>()
.HasMany(a => a.zone.cave.team)
.WithRequired()
.WillCascadeOnDelete(true);
}
我得到一个例外:
System.InvalidOperationException
HResult = 0x80131509
Message =表达式'a => a.zone.beach.team'不是有效的属性表达式。该表达式应表示一个属性:C#:'t => t.MyProperty'VB.Net:'Function(t)t.MyProperty'。
来源= EntityFramework
堆栈跟踪:
在System.Data.Entity.Utilities.ExpressionExtensions.GetSimplePropertyAccess(LambdaExpression propertyAccessExpression)
位于System.Data.Entity.ModelConfiguration.EntityTypeConfiguration 1.HasMany[TTargetEntity](Expression
1 navigationPropertyExpression)