1

MVC アプリケーションで CRUD 操作を実行するための最良の/効率的な方法を提案してください。プロジェクトでデータベース アクセス用に Entity Framework を使用しています。

例: EDMX: SupportContext ;

  1. ここでは、SupportContext [.edmx} を使用して CRUD 操作を実行しました。リポジトリよりも速く処理されます。また、LinQ クエリで複数のコンテキスト オブジェクト [テーブル] からデータを取得することもできます。

元:

using (SupportContext support =new SupportContext())
{
var=(from t1 in support.table1
     from t2 in support.table 2
     where t1.id==t2.id
     select t1).ToList();
}
  1. EDMx で直接アクセスする代わりに、汎用リポジトリ パターンを使用しました。コード ロジックと EDMX ファイルの間のレイヤーとして機能します。一般的な例を見つけてください。

コード:

public interface IRepository<T> : IDisposable where T : class
{
    IEnumerable<T> Find(Expression<Func<T, bool>> predicate);      
    void Add(T entity);              
    void SaveChanges();
}

public class GenericRepository<T> : IRepository<T> where T : class
{
    private ObjectContext _context;
    private IObjectSet<T> _objectSet;
    public GenericRepository(ObjectContext context)
    {
        _context = context;
        _objectSet = _context.CreateObjectSet<T>();
    }

    public IEnumerable<T> Find(Expression<Func<T, bool>> predicate)
    {
        return _objectSet.Where<T>(predicate);
    }                 

    public void Add(T entity)
    {
        if (entity == null)
        {
            throw new ArgumentNullException("entity");
        }
        _objectSet.AddObject(entity);
    }        

    public void SaveChanges()
    {
        _context.SaveChanges();
    }             
}

ここでは、CRUD 操作にこのリポジトリを次のように使用しました。

var dat1=new GenericRepository<Table1>(new SupportContext());
var dat2=new GenericRepository<Table2>(new SupportContext());

ここでは、dat1 と dat2 の両方のリポジトリのレコードを取得したいのですが、ID フィールドは同じです。しかし、コンバインでリトリーブできません。しかし、単一の方法でそれを行います。

var=dat1.Find(t=>t.id==3).toList();

結合されたリポジトリからデータを取得する方法と、データにアクセスするための最良の方法を提案してください。

4

0 に答える 0