1

i am trying to make a small data access framework using EF6. In all examples, i got there are Repository classes for tables in the database.

eg: ProductRepository.cs , CustomerRepository.cs etc.

But ,i want to make it generic

my bdcontext is

public class EFDbContext<T> : DbContext where T : class
{
    public DbSet<T> Entity { get; set; }
}

and IRepository interface

 public interface IRepository<TEntity> where TEntity : class
{
    List<TEntity> FetchAll();
    IQueryable<TEntity> Query { get; }
    void Add(TEntity entity);
    void Delete(TEntity entity);
    void Save();
}

and SqlRepository class

 public class SqlRepository<T> : IRepository<T> where T : class
{
    EFDbContext<T> db;
    public SqlRepository(EFDbContext<T> db)
    {
        this.db = db;
    }

    public IQueryable<T> Query
    {
        get { return db.Entity; }
    }

    public List<T> FetchAll()
    {
        return Query.ToList();
    }

    public void Add(T entity)
    {
        db.Entity.Add(entity);
    }

    public void Delete(T entity)
    {
        db.Entity.Remove(entity);
    }

    public void Save()
    {
        db.SaveChanges();
    }
}

But it is not working properly.

i used two entities :

 public class Product
{
    public int ProductID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Category { set; get; }
    public decimal Price { get; set; }
    public decimal test { get; set; }

}

public class Customer
{
    public int CustomerID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string Category { set; get; }
    public decimal Price { get; set; }
    public decimal test { get; set; }

}

but when i use code first feature of EF6 its creating two database named customer and product instead of two tables in same database

is there any mistake in my code? i am very new to EF,

please help..

Thank you

1 Answer 1

2

You don't need a generic context. The context is an abstraction over the database; you don't want multiple different versions of it.

Your generic repository approach is fine.

Change your DbContext to be not generic and have your generic repository reference the DbContext.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.