与实体框架的关系问题

时间:2012-12-14 19:04:30

标签: c# entity-framework

我需要帮助在实体框架中创建关系,因为我尝试过的所有内容都会在尝试添加迁移时给出错误,或者如果我被传递,那么我会尝试更新数据库并获得有关同名索引的错误。

public class Profile
{
    public Profile()
    {
        Environments = new HashSet<Environment>();
    }

    [Key]
    public int Id { get; set; }

    public string VersionCreated { get; set; }

    public string DiskLocation { get; set; }

    public string Name { get; set; }

    public DateTime DateTime { get; set; }

    public virtual Product Product { get; set; }

    public virtual Instance OriginalInstance { get; set; }

    public virtual ICollection<Environment> Environments { get; set; } 
}


public class Instance
{
    public Instance()
    {
        TestResults = new HashSet<TestResult>();
        Environments = new HashSet<Environment>();
    }

    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    public string Version { get; set; }

    public string UserFriendlyName { get; set; }

    public virtual Product Product { get; set; }

    public virtual Profile LastKnownProfile { get; set; }

    public virtual Computer Computer { get; set; }

    public virtual ICollection<TestResult> TestResults { get; set; }

    public virtual ICollection<Environment> Environments { get; set; } 
}

上述类的问题是,Profile类上的OrginalInstance属性和Instance类中的LastKnownProfile应该只是这些特定表的外键,它们可能不会经常相同。它们也可能都是空的。

我试过了:

modelBuilder.Entity<Instance>().HasRequired(i => i.LastKnownProfile);
modelBuilder.Entity<Profile>().HasRequired(p => p.OriginalInstance);

这给了我一个Unable to determine the principal end of an association between the types 'EcuWeb.Data.Entities.Instance' and 'EcuWeb.Data.Entities.Profile'. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.错误。

和:

modelBuilder.Entity<Instance>().HasRequired(i => i.LastKnownProfile).WithOptional();
modelBuilder.Entity<Profile>().HasRequired(p => p.OriginalInstance).WithOptional();

数据库将外键引用添加回自身。

1 个答案:

答案 0 :(得分:1)

  

...那个Profile类上的OrginalInstance属性和   Instance类中的LastKnownProfile应该只是外来的   这些特定表的键,它们可能不一样   经常。它们也可能都是空的。

在这种情况下,如果我不误解您的引用,那么您实际上希望在ProfileInstance之间两个一对多关系。这意味着许多配置文件可以具有相同的OriginalInstance,并且许多实例可以具有相同的LastKnownProfile。正确的映射将如下所示:

modelBuilder.Entity<Profile>()
    .HasOptional(p => p.OriginalInstance)
    .WithMany()
    .Map(m => m.MapKey("OriginalInstanceId"));

modelBuilder.Entity<Instance>()
    .HasOptional(i => i.LastKnownProfile)
    .WithMany()
    .Map(m => m.MapKey("LastKnownProfileId"));

MapKey行是可选的。如果没有它们,EF将创建一个具有默认名称的外键。

另请注意,如果“两者都可能为空”,则必须使用HasOptional(而非HasRequired)。