I have a table named ServiceProviders with static data. The POCO class is follows
public class ServiceProvider
{
public virtual int Id
{
get;
set;
}
public virtual string Name
{
get;
set;
}
}
I have a Client table. Each client needs to have a reference to one of the “existing” service providers.
public class Client
{
public virtual int Id
{
get;
set;
}
public virtual string FirstName
{
get;
set;
}
public virtual string LastName
{
get;
set;
}
public virtual ServiceProvider ServiceProvider
{
get;
set;
}
}
I am configuring the client using EF code first fluent API as follows
public ClientConfiguration(): base()
{
HasKey(e => e.Id);
Property(e => e.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
ToTable("dbo.Clients");
Property(e => e.FirstName).IsRequired().HasMaxLength(256).IsVariableLength().HasColumnType("nvarchar");
Property(e => e.LastName).IsRequired().HasMaxLength(256).IsVariableLength().HasColumnType("nvarchar");
HasRequired(e => e.ServiceProvider).WithMany().Map(m => m.MapKey("ServiceProviderId")).WillCascadeOnDelete(false);
}
When I want to insert a new client’s record, I get a reference of an existing ServiceProvider instance and attach it to the Client’s ServiceProvider property
Client client = new Client() { FirstName = "John", LastName = "Doe" };
client.ServiceProvider = serviceproviders[0]; //An existing ServiceProvider instance fetched from DB earlier
When I call SaveChanges, EF inserts a new (duplicate) record in my ServiceProviders table. All I want it to do is to insert a new record only in the Client Table and set the value of ServiceProviderId column to the existing ServiceProvider instance’s Id.
What am I doing wrong?
You need to attach the existing
ServiceProviderto the context you are saving the newClientin.Attachtells EF that the ServiceProvider already exists in the database and prevents an INSERT for that ServiceProvider: