2013-12-10 27 views
0

實體框架是否有一些自動化的迷人功能,這意味着我不必重新編寫crud控制器和視圖來與我的工作庫和統一的框架注射:(?實體框架構建視圖和控制器...我必須重新工作到我的倉庫

它明確地引用了控制器的EntityFramework數據庫環境......然後做實際的數據操作的控制器裏面自己...

例如,該結束了,我控制器:

[HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Create([Bind(Include="ProductID,Title")] Product product) 
    { 
     if (ModelState.IsValid) 
     { 
      db.Products.Add(product); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     return View(product); 
    } 

當真的.Add和.SaveChanges需要在我的存儲庫...

我不想編寫50 CRUD操作或複製和粘貼視圖和控制器每次我想創建的東西。 ..有自動

大概是這樣的一種方式:

namespace WebApplication.Domain.Abstract 
{ 
    public interface IProductRepository 
    { 
     IQueryable<Product> Products { get; } 
     Product Create(Product product); 
     ... yada yada crud operations 
    } 
} 

public class EFProductRepository : IProductRepository 
{ 
    private EFDbContext context = new EFDbContext(); 

    public IQueryable<Product> Products 
    { 
     get { return context.Products; } 
    } 

//... implements all the CRUD operations that entity framework ends up placing inside the controller 
} 
+0

發佈一些代碼將是非常有益的。很難理解你在這裏問的問題。 –

+0

你很快:)我實際上在完成之前意外地提交了問題;)soz ...現在完成 – Jimmyt1988

+1

你想自動化什麼?如果是代碼生成,那麼T4 http://msdn.microsoft.com/en-us/library/bb126445.aspx可能是你正在尋找的。 –

回答

0

因爲根據意見,這是什麼解決了這個問題:

Visual Studio爲基於模板的代碼生成提供了一種內置的方式。它被稱爲T4,你可以閱讀更多關於它here

0

的通用Repository<TPoco>是這裏的通用方法。

ie 1 Repository重複使用每個POCO。

它也通常與工作單元模式結合使用,將更新合併到邏輯工作單元中。

這裏是一個基本的演示來說明這一點。 但是,理想的情況是在覈心層 中聲明IRepository,並且數據訪問層實現Repositiry:IRepository以將參考文獻 保留在覈心域層之外。 (這是研究的另一重要相關的代碼結構物) 此演示太短IRepository<t>

using System; 
using System.Collections.Generic; 
using System.Globalization; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 

namespace repofT 
{ 
class Program 
{ 
    static void Main(string[] args) 
    { 
     // Kick Start Repository of T demo 
     // There are advance models combining context creation/unit of work and repository. 
     // The concept of Inversion of Control/Dependency injection should be inestigated 
     // for the people new to IOC 
     // SIMPLIFIED Unit of Work and Respository of T sample 
     var ctx = new MyContext(); 
     var uow = new UnitOfWork(ctx); 
     var rep = new Repository<MyPoco>(ctx); 

     addTest(rep, uow); 

     var poco1 = FindTest(rep); 

     ChangeTest(poco1, rep, uow); 

     Console.ReadKey(); 
    } 

    private static void ChangeTest(MyPoco poco1, Repository<MyPoco> rep, UnitOfWork uow) 
    { 
     poco1.Content = "Test - was changed"; 
     rep.Change(poco1); 
     uow.Commit(); 
     DumpTest(rep); 
    } 

    private static MyPoco FindTest(Repository<MyPoco> rep) 
    { 
     var poco1 = rep.Find(1); 
     Console.WriteLine(poco1.Id + " : " + poco1.Content); 
     return poco1; 
    } 

    private static void addTest(Repository<MyPoco> rep, UnitOfWork uow) 
    { 
     var mypoco = new MyPoco() 
     { 
      Content = "Test" + System.DateTime.Now.ToString(CultureInfo.InvariantCulture), 
     }; 
     rep.Add(mypoco); 
     uow.Commit(); 

     DumpTest(rep); 
    } 

    private static void DumpTest(Repository<MyPoco> rep) 
    { 
     var pocoList = rep.GetList(t => t.Content.StartsWith("Test")); 
     if (pocoList != null) 
     { 
      foreach (var poco in pocoList) 
      { 
       Console.WriteLine(poco.Id + " : " + poco.Content); 
      } 
     } 
    } 
} 
} 

和工作上下文類的庫/股

using System; 
using System.Collections.Generic; 
using System.ComponentModel.DataAnnotations.Schema; 
using System.Data.Entity; 
using System.Linq; 
using System.Data.Entity.Validation; 
using System.Linq.Expressions; 

namespace repofT 
{ 
/// <summary> 
/// Note to the reader. NO error handling. You should add your preferred solution. 
/// This is a stripped down sample to illustrate how Repository of T pattern works. 
/// </summary> 

public class MyContext : DbContext 
{ 
    public DbSet<MyPoco> MyPocos { get; set; } 

    protected override void OnModelCreating(DbModelBuilder modelBuilder) 
    { 
     //fluent API.... 
     base.OnModelCreating(modelBuilder); 
     var entity = modelBuilder.Entity<MyPoco>(); 
     entity.HasKey(t => t.Id) ; 
     entity.Property(t => t.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); 
    } 
} 

public class MyPoco 
{ 
    //virtuals for EF, especially Proxies and navigation, Use public get/set 
public virtual int Id { get; set; } 
public virtual string Content { get; set; } 
} 

public class Repository<TPoco> where TPoco : class, new() 
{ 
    public DbContext Context { get; private set; } 

    public Repository(DbContext context){ 
     Context = context; 
    } 

    public IList<TPoco> GetList(Expression<Func<TPoco, bool>> predicate) 
    { 
     // Investigate returning IQueryable versus IList as you learn more. 
     return GetQuery(predicate).ToList(); 
    } 
    public IQueryable<TPoco> GetQuery(Expression<Func<TPoco, bool>> predicate) 
    { 
     // Investigate returning IQueryable versus IList as you learn more. 
     return Context.Set<TPoco>().Where(predicate); 
    } 
    public TPoco Get(Expression<Func<TPoco, bool>> predicate) 
    { 
     return Context.Set<TPoco>().FirstOrDefault(predicate); 
    } 

    public TPoco Find(params object[] keyValues) 
    { 
     return Context.Set<TPoco>().Find(keyValues); 
    } 

    public TPoco Attach(TPoco poco) 
    { 
     return Context.Set<TPoco>().Add(poco); 
    } 
    public TPoco Add(TPoco poco){ 
     return Context.Set<TPoco>().Add(poco); 
    } 

    public TPoco AddOrUpdate(TPoco poco){ 
     return Context.Set<TPoco>().Add(poco); 
    } 

    public TPoco Remote(TPoco poco){ 
     return Context.Set<TPoco>().Remove(poco); 
    } 

    public void Change(TPoco poco){ 
     Context.ChangeTracker.DetectChanges(); 
    } 

    public void SetEntityState(TPoco poco, EntityState state = EntityState.Modified){ 
     Context.Entry(poco).State = state; 
    } 
} 


public class UnitOfWork 
{ 
    public DbContext Context { get; protected set; } 

    public UnitOfWork(DbContext context){ 
     Context = context; 
    } 
    public IEnumerable<DbEntityValidationResult> GetDbValidationErrors() { return 
     Context.GetValidationErrors(); 
    } 

    public int Commit() 
    { 
     try { 
      var recs = Context.SaveChanges(); 
      return recs; 
     } 
     catch (DbEntityValidationException efException){ 
      var errors = GetDbValidationErrors(); // DO SOMETHING HERE !!!!! 
      return -1; 
     } 
    } 

} 
}