与关系冲突和外键1-1

时间:2011-12-30 13:16:59

标签: 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 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
      }
 }

我无法理解如何添加Configuration并设置IdCompany。 还有另一种方法吗? 我怎么能这样做?

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

1 个答案:

答案 0 :(得分:1)

你做不到。仅当依赖实体将FK作为主要实体作为主键时,才支持一对一关系。这意味着Configuration.IdConfiguration的PK,也是Company.Id的FK。

您无法使用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);