Khan
Khan

Reputation: 38

Entity Framework Map Model To Table

I have following method in my Project.

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

Then my DbContext has this..

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

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

        }

This works fine, as long as "Product" Model is within same project.

However, different clients will be consuming my DataAccess layer and they will be passing Models of different types. How can I tell EntityFramework to dynamically Bind a Model to a "Table" in SQL server.

Upvotes: 0

Views: 727

Answers (1)

Khan
Khan

Reputation: 38

I was able to resolve this problem by doing the following.

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 the steps are...

  • A. Class must inherit DbContext.
  • A Generic Property for DbSet.

Now DbSet is a Generic Table, which you can use in your Generic Repoitory.

Upvotes: 1

Related Questions