2

Entity Framework を使用してデータベースに行を追加するメソッドを持つジェネリック C# クラスを作成したいと考えています。

というテーブルが 1 つありますAddress。データベースに住所を追加するために、次のコードを作成しました。

public class AddressExchange
{
    public int Insert(Address address)
    {
        using (var db = new DemoWebEntities())
        {
            //db.AddObject("Address", address);
            db.Addresses.AddObject(address);
            db.SaveChanges();
            return address.Id;
        }
    }
}

EDMX 内の任意のエンティティに対してこの操作を実行するジェネリック クラスを作成したいと考えています。私はそれが次のように見えるべきだと思います:

public class EntityExchange<T, KeyType>
{
    public KeyType Insert(T t)
    {
        using (var db = new DemoWebEntities())
        {
            // The entity set name might be wrong.
            db.AddObject(typeof(T).Name, t);                

            // EF doesn't know what the primary key is.
            return t.Id;
        }
    }
}

メソッドを使用してオブジェクトをデータベースに追加することは可能かもしれないと思いますAddObjectが、特に複数形の場合、entityset 名は型名と必ずしも同じではありません!

また、主キーを呼び出し元に返したいのですが、どのフィールドに主キーが含まれているかを知る方法がわかりません。

4

4 に答える 4

3

プロキシの作成も保証する汎用リポジトリに汎用 InsertOrUpdate メソッドがあります。(遅延読み込みをサポートするにはプロキシが必要です。「new」を使用してエンティティを作成すると、プロキシは作成されません)。ここで質問を参照してください

public class RepositoryBase<T> : IRepository<T> where T : ModelBase
{
    public virtual T InsertOrUpdate(T e)
    {
        DbSet<T> dbSet = context.Set<T>();

        //Generate a proxy type to support lazy loading
        T instance = dbSet.Create();

        DbEntityEntry<T> entry;
        if (e.GetType().Equals(instance.GetType()))
        {
            //The entity being added is already a proxy type that 
            //supports lazy loading just get the context entry
            entry = context.Entry(e);
        }
        else
        {
            //The entity being added has been created using the "new" operator. 
            //Attach the proxy
            //Need to set the ID before attaching or we get 
            //The property 'ID' is part of the object's key 
            //information and cannot be modified when we call SetValues
            instance.ID = e.ID;
            entry = context.Entry(instance);
            dbSet.Attach(instance);

            //and set it's values to those of the entity
            entry.CurrentValues.SetValues(e);
            e = instance;
        }

        entry.State = e.ID == default(int) ?
                                EntityState.Added :
                                EntityState.Modified;

        return e;
    }
}

public abstract class ModelBase
{
    public int ID { get; set; }
}

すべてのモデルが ModelBase を継承しているため、ID の問題が処理され、ID だけでなくエンティティが返されることに注意してください。エンティティへの参照が渡され、とにかく EF が ID の修正を実行するため、渡された参照からいつでもアクセスできるため、これはおそらく厳密には必要ありません。

于 2013-07-20T09:48:28.530 に答える
2

これは Entity フレームワークの特定のバージョンに依存している可能性がありますが、これが私のやり方です

public void Create(T entity)
{
    using (var db = new DemoWebEntities())
    {
        db.Set<T>().Add(entity);
    }
}
于 2013-07-19T14:53:18.537 に答える