Shyam Sundar
Shyam Sundar

Reputation: 49

How to configure muliple relationships in fluent api using code first?

I am receiving following exception while running the code

An object of type 'System.Collections.Generic.HashSet`1[[SolutionName.ProjectName.Contract, SolutionName.ProjectName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' cannot be set or removed from the Value property of an EntityReference of type 'SolutionName.ProjectName.Contract'.

I have two tables Contract table and Client table

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; }
}

So we have 3 navigation properties to contract from client table.Contract1 and contract2 from client table will have single rows each. But iam looking to have multiple contracts to be mapped inside the collection of contracts.i have tried this one using following fluent api code:

modelBuilder.Entity<Client>()
                    .HasOptional(c => c.Contracts)
                    .WithMany()
                    .HasForeignKey(b => b.Contract1Id);

                modelBuilder.Entity<Client>()
                   .HasRequired(c => c.Contracts)
                   .WithMany()
                   .HasForeignKey(b => b.Contract2Id);

iam not able correctly configure the fluent api for my scenario.please give some suggestion

Upvotes: 2

Views: 51

Answers (1)

Shyam Sundar
Shyam Sundar

Reputation: 49

Here i have many contracts with one client. In other words A client can have many contracts with clientId as FK in contracts. So following simple fluent API code has worked for me.

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);

Upvotes: 1

Related Questions