1

移行を追加しようとしたときにエラーが発生するか、それが渡された場合はデータベースを更新して同じ名前のインデックスに関するエラーが発生するため、エンティティフレームワークで関係を作成するのに助けが必要です。

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 が、これらの特定のテーブルへの外部キーであると想定されており、おそらく同じであるとは限らないことです。また、両方が null になる可能性もあります。

私が試してみました:

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

データベースは外部キー参照を自身に追加します。

4

1 に答える 1

1

... ProfileクラスのOrginalInstanceプロパティとInstanceクラスのLastKnownProfileは、これらの特定のテーブルへの外部キーであると想定されており、おそらく同じになることはあまりありません。また、両方ともnullになる可能性があります。

この場合、あなたは実際に2つの1対多の関係を望ん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はデフォルト名で外部キーを作成します。

また、「両方がnullになる可能性がある」場合HasOptionalは、(の代わりに)を使用する必要があることにも注意してください。HasRequired

于 2012-12-14T19:24:58.840 に答える