Entity framework 与关系和外键冲突1-1

Entity framework 与关系和外键冲突1-1,entity-framework,ef-code-first,foreign-key-relationship,Entity Framework,Ef Code First,Foreign Key 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

我正试图建立这种关系

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

你不能。当前仅当从属实体的主键为FK to principal entity时,才支持一对一关系。这意味着
Configuration.Id
Configuration
的主键,但也是对
Company.Id
的主键

无法使用
CompanyId
的原因是数据库需要使用唯一索引(否则它将不是一对一的关系,而是一对多的关系),而EF目前不支持唯一索引

编辑:

对不起。现在我更明白你的问题了。如果您知道该公司的Id,并且希望将其添加到新配置中,则可以尝试执行以下操作:

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

明白,但我如何为公司设定价值?我必须检索公司并设置配置。公司=公司?我添加了一些示例。它在一对多的情况下工作没有任何问题,所以我希望它也能在一对一的情况下工作。
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);