2017-03-07 76 views
0

我在我的项目中有以下方法。实体框架地图模型到表

public IEnumerable<T> GetAll() 
    { 
     return _context.Set<T>().ToList(); 
    } 

然后我的DbContext有这个..

 protected override void OnModelCreating(DbModelBuilder modelBuilder) 
     { 

       Entity<Product>.ToTable("Product"); 

     } 

这工作得很好,只要 “产品” 型号是同一个项目中。

但是,不同的客户端将使用我的DataAccess层,他们将传递不同类型的模型。我如何告诉EntityFramework动态地将模型绑定到SQL服务器中的“表”。

+0

他们可以提供自己的[EntityTypeConfiguration]类(http://www.entityframeworktutorial.net/code-first/entitytypeconfiguration-class.aspx)。 –

+0

我很难找到它的一个例子 – Khan

回答

0

我能够通过执行以下操作来解决此问题。

public class Repository<T> : DbContext, IRepository<T> where T : BaseModel 
{ 

    public DbContext _context { get; set; } 
    public DbSet<T> _dbSet { get; set; } 

    public Repository(string con) 
     : base(con) 
    { 

    } 

    public IEnumerable<T> GetAll() 
    { 
     return _dbSet; 
    } 

    public void Add(T entity) 
    { 
     _dbSet.Add(entity); 
     _context.SaveChanges(); 
    } 


} 

Basicly的步骤...

  • A.类必须继承的DbContext。
  • DbSet的通用属性。

现在DbSet是一个通用的表,你可以在你的通用Repoitory使用。