3

次のように結合テーブルの名前を指定しようとすると、エンティティ フレームワークに問題が発生します。

// Used by a bunch of things...
public abstract BaseClass
{
    public int Id { get; set; }
    public string Name { get; set; }
}

public abstract ThingsBaseClass : BaseClass
{
    public virtual ICollection<Things> Things { get; set; }    
}

public First : ThingsBaseClass
{
    // This holds items of type First and doesn't have any other properties
}

public Second : ThingsBaseClass
{
    // This holds items of type Second and doesn't have any other properties
}

public Things
{
    public int Id { get; set; }
    public string Description { get; set; }

    // Many to Many
    public virtual ICollection<First> Firsts { get; set; }
    public virtual ICollection<Second> Seconds { get; set; }
}

したがって、テーブルが次のとおりであることを除いて、すべてが正常に機能します。

First
FirstThings
Second
SecondThings
Things

名前を次のように変更しようとしています:

First
Second
ThingFirsts
ThingSeconds
Things

次のコードを使用して名前を変更しようとすると、非常に奇妙でランダムなエラーが発生します。

public class ThingConfiguration : EntityTypeConfiguration<Thing>
{
    HasMany(x => x.Firsts)
        .WithMany(x => x.Things)
         .Map(x => x.ToTable("ThingFirsts"));

    HasMany(x => x.Firsts)
        .WithMany(x => x.Things)
        .Map(x => x.ToTable("ThingSeconds"));    
}

Code First Migrations を使用してデータベースを更新しようとしています (または、最初から作成するだけです)。

エラーには次のようなものがあります。

Schema specified is not valid. Errors: (28,6) : error 0040: Type Thing_First is not defined in namespace Project.Domain.Repositories (Alias=Self).

また

Schema specified is not valid. Errors: (126,6) : error 0074: NavigationProperty 'Thing' is not valid. Type 'Project.Domain.Repositories.Second' of FromRole 'Thing_Firsts_Target' in AssociationType 'Project.Domain.Repositories.Thing_Second' must exactly match with the type 'Project.Domain.Repositories.First' on which this NavigationProperty is declared on.

First と Second の継承を取り除き、直接 に入れると、問題Idなく動作します。NameICollection<Thing> Things

継承を使用する理由はありませんが、ほぼ同じBaseClasses を持つこれらのオブジェクトが約 5 つあり、それを DRY に保ちたいと考えています。

弾丸をかじって、コードをどこでも繰り返して、Entity Framework をよりシンプルに保つ必要がありますか?

簡単なものがありませんか?継承されたクラスを使用して遭遇する他の「落とし穴」はありますか?

EF 6 はこれをより適切にサポートしていますか?

4

1 に答える 1

0

モデルクラス定義で属性を使用するだけです。

[TableName("WhateverYouWant")]
public class First{} 

「継承よりも構成を優先する」ことを検討し、共有値を基本クラスではなくプロパティとして扱い、インターフェイスを使用してそれらをポリモーフィックに処理することをお勧めします。DRY は重要ですが、動作にはさらに重要です。同じプロパティを持つ 2 つのオブジェクトによって、基本クラスが自動的に生成されることはありません。同じ動作を持つ 2 つのクラスは生成される可能性が高くなります。継承やその他のオブジェクト指向の方法論は、データやプロパティの正規化ではなく、動作の正規化に関するものです。同じインターフェイスを実装する 2 つのクラスはすべて、重複するプロパティ定義を持つことになります。それで大丈夫です。

于 2013-02-17T19:29:54.760 に答える