给出以下数据库模型
我有两个流畅的实体框架配置,一个在我读取时工作(设置了setupFields列表),另一个用于写入,如果我也用于读取,则总是带有一个空的SetupFields列表
[Table("[BALANCE.SETUP]")]
public class SetupEntity
{
[Key]
public Guid Id { get; set; }
public string Title { get; set; }
public virtual ChassisEntity Chassis { get; set; }
public virtual EventEntity Event { get; set; }
public virtual ICollection<SetupFieldEntity> SetupFields { get; set; }
}
[Table("[BALANCE.SETUP.FIELD]")]
public class SetupFieldEntity
{
[Key]
[Column(Order = 0)]
public Guid SetupId { get; set; }
[Key]
[Column(Order = 1)]
public int Sequence { get; set; }
public string Section { get; set; }
public string Name { get; set; }
public string Value { get; set; }
public virtual SetupEntity Setup { get; set; }
}
(可以阅读)
modelBuilder.Entity<SetupEntity>()
.HasMany(x => x.SetupFields)
.WithRequired(x => x.Setup)
.Map(x => x.MapKey("SETUPID"));
(可以写)
modelBuilder.Entity<SetupEntity>()
.HasMany(x => x.SetupFields)
.WithRequired()
.HasForeignKey(x => x.SetupId);
如果我使用读取配置来读取,这是我得到的错误:
在SET子句中多次指定列名“SETUPID”。在同一SET子句中不能为列分配多个值。修改SET子句以确保列只更新一次。如果SET子句更新视图的列,则列名“SETUPID”可能在视图定义中出现两次。
更新1
为了清楚说明,模型是延迟加载的,我明确地将它们包含在内,因此,在使用第一个配置时,模型按预期设置:
if (includeFields)
{
x = x.Include(entity => entity.SetupFields);
}
更新2
根据下面的评论,我将映射更改为只在插入时有效,但在读取子集合时仍为空:
modelBuilder.Entity<SetupEntity>().HasMany(x => x.SetupFields);
[Table("[BALANCE.SETUP]")]
public class SetupEntity
{
[Key]
public Guid Id { get; set; }
public string Title { get; set; }
public virtual ChassisEntity Chassis { get; set; }
public virtual EventEntity Event { get; set; }
public virtual ICollection<SetupFieldEntity> SetupFields { get; set; }
}
[Table("[BALANCE.SETUP.FIELD]")]
public class SetupFieldEntity
{
[Key]
[Column(Order = 0)]
public Guid SetupId { get; set; }
[Key]
[Column(Order = 1)]
public int Sequence { get; set; }
public string Section { get; set; }
public string Name { get; set; }
public string Value { get; set; }
public virtual SetupEntity Setup { get; set; }
}
更新3
根据评论我完全从实体中删除了属性,但collection属性仍为null:(
public class SetupEntity
{
public Guid Id { get; set; }
public string Title { get; set; }
public virtual ChassisEntity Chassis { get; set; }
public virtual EventEntity Event { get; set; }
public virtual ICollection<SetupFieldEntity> SetupFields { get; set; }
}
[Table("[BALANCE.SETUP.FIELD]")]
public class SetupFieldEntity
{
public Guid SetupId { get; set; }
public int Sequence { get; set; }
public string Section { get; set; }
public string Name { get; set; }
public string Value { get; set; }
public virtual SetupEntity Setup { get; set; }
}
modelBuilder.Entity<SetupEntity>()
.HasKey(x => x.Id)
.HasMany(x => x.SetupFields)
.WithRequired(x => x.Setup);
modelBuilder.Entity<SetupFieldEntity>()
.HasKey(x => x.SetupId)
.HasKey(x => x.Sequence);
欢迎任何帮助。感谢