【问题标题】:How to configure muliple relationships in fluent api using code first?如何首先使用代码在fluent api中配置多个关系?
【发布时间】: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


    【解决方案1】:

    在这里,我与一位客户签订了许多合同。换句话说,一个客户可以有许多合同,其中 clientId 作为合同中的 FK。所以遵循简单流畅的 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);
    
            modelBuilder.Entity<Client>()
                        .HasMany(c => c.Contracts)
                        .WithRequired()
                        .HasForeignKey(a => a.ClientId);
    

    【讨论】:

      猜你喜欢
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-20
      • 2021-04-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多