【发布时间】:2019-04-06 20:32:53
【问题描述】:
我在运行代码时收到以下异常
类型的对象 'System.Collections.Generic.HashSet`1[[SolutionName.ProjectName.Contract, 解决方案名称.项目名称,版本=1.0.0.0,文化=中性, PublicKeyToken=null]]' 不能从值中设置或删除 EntityReference 类型的属性 'SolutionName.ProjectName.Contract'。
我有两张表 Contract 表和 Client 表
public partial class Contract
{
public int ContractId { get; set; }
public System.Guid Guid { get; set; }
//nav props
public virtual Client Client { get; set; }
}
public partial class Client
{
public int Id { get; set; }
public System.Guid Guid { get; set; }
public String ClientName { get; set; }
public Nullable<int> Contract1Id { get; set; } //foreign key pointing to ContractId
public Nullable<int> Contract2Id { get; set; } //foreign key pointing to ContractId
//nav props
public virtual ICollection<Contract> Contracts { get; set; }
public virtual Contract Contract1 { get; set; }
public virtual Contract Contract2 { get; set; }
}
所以我们有 3 个导航属性可以从客户端表中收缩。客户表中的 Contract1 和 contract2 将各有一行。 但是我希望在合同集合中映射多个合同。我已经使用以下流畅的 api 代码尝试了这个:
modelBuilder.Entity<Client>()
.HasOptional(c => c.Contracts)
.WithMany()
.HasForeignKey(b => b.Contract1Id);
modelBuilder.Entity<Client>()
.HasRequired(c => c.Contracts)
.WithMany()
.HasForeignKey(b => b.Contract2Id);
我无法为我的场景正确配置 fluent api。请给一些建议
【问题讨论】:
标签: c# entity-framework asp.net-web-api ef-code-first ef-fluent-api