Kim Tranjan
Kim Tranjan

Reputation: 4541

Conflict with relationship and foreign key 1-1

I'm trying to do this relationship

 public class Company {
      public int Id { get; set; }

      public Configuration Configuration { get; set; }
 }

 public class Configuration {
      public int Id { get; set; }

      // public int CompanyId { get; set; } -> can't do this

      public Company Company { get; set; }
 }

 public class ConfigurationMapping : EntityTypeConfiguration<Configuration> {
      public ConfigurationMapping {
           HasRequired(configuration => configuration.Company)
                .WithOptional(company => company.Configuration)
                // .HasForeignKey(configuration => configuration.CompanyId) -> this doesn't exist
                .Map(f => f.MapKey("CompanyId")); // that's why I can't use the property above
      }
 }

I can't understand how I can add a Configuration and set the IdCompany. There's another approach? How can I do this?

db.Configurations.Add(new Configuration {
    IdCompany = idCompany
});
db.SaveChanges();

Upvotes: 0

Views: 702

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364269

You cannot. One-to-one relation is currently supported only if dependent entity has FK to principal entity as its primary key. It means that Configuration.Id is PK of Configuration but also FK to Company.Id.

The reason why you cannot use CompanyId is that database would require it to use unique index (otherwise it would not be one-to-one relation but one-to-many) and EF currently doesn't support unique indexes.

Edit:

Sorry. Now I better understand your question. If you know the Id of the company and you want to add it a new configuration you can try to do something like this:

var company = new Company { Id = companyId }; 
context.Companies.Attach(company);  // Existing company, EF know thinks it was loaded from DB

var configuration = new Configuration { Company = company }; // Create relation with existing company. It must not be related to other configuration!
context.Configurations.Add(configuration);

Upvotes: 1

Related Questions