2

データベース層にコードファーストパターンを使用しています。

私は2つのPOCOクラスを持っています:

public class Order
{
    [Key]
    public int OrderId { get; set; }
    public virtual ICollection<Item> Items { get; set; }
    // other fields
}

public class Item
{
    [Key]
    public int ItemId { get; set; }
    public virtual ICollection<Order> Orders { get; set; }
    // other fields
}

次に、データ コンテキスト クラスがあります。

public class DataContext : DbContext
{
    public DbSet<Item> Items { get; set; }
    public DbSet<Order> Orders { get; set; }
}

そして、私は「リポジトリ」クラスを持っています:

public class OrderRepository
{
    private DataContext dataContext = new DataContext();
    public void Save(Order entity)
    {
        entity.OrderDate = System.DateTime.Now;
        dataContext.Orders.Add(entity);
        dataContext.SaveChanges();
    }
}

この OrderRepository.Save メソッドを呼び出すと、エラーが発生します。エンティティ オブジェクトは、IEntityChangeTracker の複数のインスタンスによって参照できません。

データベースには、Items、Orders、Items_Orders というテーブルがあります。このエラーと EF の多対多の保存について、Google でいろいろ調べましたが、役に立ちそうなものは見つかりませんでした。 Code-First 原則のサンプルを見つけます。

ありがとう!

4

1 に答える 1

5

DataContextあなたはおそらくあなたのエンティティに関連する他のから来た他のエンティティ(他のリポジトリから?)を持っていますOrder。それはあなたが見ているエラーを引き起こすでしょう。

すべてのリポジトリはDataContext、作業単位で同じものを共有する必要があります。通常、これは次のようにコンストラクタインジェクションを使用して行います。

public class OrderRepository
{
    private readonly DataContext dataContext;
    public void Save(Order entity)
    {
        entity.OrderDate = System.DateTime.Now;
        dataContext.Orders.Add(entity);
        dataContext.SaveChanges();
    }

    public OrderRepository(DataContext dataContext)
    {
        this.dataContext = dataContext;
    }
}
于 2010-09-01T12:39:45.080 に答える