ASP.NET Web Api and Autofac IoC. Error: ExceptionMessage=None of the constructors found - asp.net-web-api

I am trying to use Autofac for IoC for my Asp.Net WebApi project. I am trying to send a simple POST request to the API, but to no avail. I have been stuck on this for some time now and can't figure it out.
Please see relevant code and advise accordingly. Your help would be greatly appreciated.
public interface IEntityRepository<T> where T : class, new()
{
IQueryable<T> All { get; }
IQueryable<T> AllIncluding(params Expression<Func<T,object>>[] includeProperties);
IQueryable<T> GetAll();
//IQueryable<T> GetSingle(string entitiesID);
IQueryable<T> FindBy(Expression<Func<T, bool>> predicate);
void Add(T entity);
void Delete(T entity);
void Edit(T entity);
void Save();
PaginatedList<T> Paginate<TKey>(int pageindex, int pagesize, Expression<Func<T, TKey>> keySelector);
PaginatedList<T> Paginate<TKey>(
int pageindex, int pagesize,
Expression<Func<T, TKey>> keySelector,
Expression<Func<T, bool>> predicate,
params Expression<Func<T, object>>[] includeProperties);
}
public class EntityRepository<T> : IEntityRepository<T> where T : class, new()
{
readonly CirclesDBEntities _entitiesContext;
public EntityRepository(CirclesDBEntities entitiesContext)
{
if (entitiesContext == null)
{
throw new ArgumentNullException("entitiesContext");
}
_entitiesContext = entitiesContext;
}
public virtual IQueryable<T> GetAll()
{
return _entitiesContext.Set<T>();
}
public IQueryable<T> All
{
get { return GetAll(); }
}
public virtual IQueryable<T> AllIncluding(params Expression<Func<T, object>>[] includeProperties)
{
IQueryable<T> query = _entitiesContext.Set<T>();
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
return query;
}
public virtual IQueryable<T> FindBy(Expression<Func<T, bool>> predicate)
{
return _entitiesContext.Set<T>().Where(predicate);
}
public virtual PaginatedList<T> Paginate<TKey>(int pageIndex, int pageSize, Expression<Func<T, TKey>> keySelector)
{
return Paginate(pageIndex, pageSize, keySelector, null);
}
public virtual PaginatedList<T> Paginate<TKey>(
int pageIndex, int pageSize,
Expression<Func<T, TKey>> keySelector,
Expression<Func<T, bool>> predicate,
params Expression<Func<T, object>>[] includeProperties)
{
IQueryable<T> query = AllIncluding(includeProperties).OrderBy(keySelector);
query = (predicate == null) ? query : query.Where(predicate);
return query.ToPaginatedList(pageIndex, pageSize);
}
public virtual void Add(T entity)
{
DbEntityEntry dbEntityEntry = _entitiesContext.Entry<T>(entity);
_entitiesContext.Set<T>().Add(entity);
}
public virtual void Edit(T entity)
{
DbEntityEntry dbEntityEntry = _entitiesContext.Entry<T>(entity);
dbEntityEntry.State = EntityState.Modified;
}
public virtual void Delete(T entity)
{
DbEntityEntry dbEntityEntry = _entitiesContext.Entry<T>(entity);
dbEntityEntry.State = EntityState.Deleted;
}
public virtual void Save()
{
_entitiesContext.SaveChanges();
}
}
public static class TermRepository
{
public static Term GetCurrentTerm(this IEntityRepository<Term> termRepository)
{
return termRepository.GetAll().OrderByDescending(x => x.DateUploaded).FirstOrDefault(); //descending puts the most recent item on top of the stack
}
}
public class TermsService : ITermsService
{
private readonly IEntityRepository<Term> _termRepository;
public TermsService(IEntityRepository<Term> termRepository)
{
_termRepository = termRepository;
}
public Term GetMostRecentTerm()
{
Term term = _termRepository.GetCurrentTerm();
return term;
}
public bool UploadNewTerm(string newTerm)
{
Term term = new Term();
term.TermID = SetAccountID();
term.Term1 = newTerm;
term.DateUploaded = DateTime.Now;
_termRepository.Add(term);
_termRepository.Save();
return true;
}
}
public interface ITermsService
{
Term GetMostRecentTerm();
bool UploadNewTerm(string Term);
}
public static class AutofacConfig
{
public static void Initialize(HttpConfiguration config)
{
Initialize(config,
RegisterServices(new ContainerBuilder()));
}
public static void Initialize(HttpConfiguration config, IContainer container)
{
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
}
private static IContainer RegisterServices(ContainerBuilder builder)
{
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
// registration goes here
//EF DbContext
builder.RegisterType<CirclesDBEntities>()
.As<DbContext>()
.InstancePerRequest();
//Repositories
builder.RegisterGeneric(typeof(EntityRepository<>))
.As(typeof(IEntityRepository<>))
.InstancePerDependency();
//this makes it check non-public classes
//builder.RegisterGeneric(typeof(EntityRepository<>))
//.As(typeof(IEntityRepository<>))
//.InstancePerRequest().FindConstructorsWith(
//new DefaultConstructorFinder(type =>
//type.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance)))
//.As(typeof(IEntityRepository<>));
//Services
builder.RegisterType<TermsService>()
.As<ITermsService>()
.InstancePerRequest();
return builder.Build();
}
}
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
//Registering routes from the WebApi.Config file
GlobalConfiguration.Configure(Config.WebApiConfig.Register);
//Registering routes from the HelpPageAreaRegistration in the areas section
GlobalConfiguration.Configure(CirclesWebApi.Areas.HelpPage.HelpPageAreaRegistration.RegisterAllAreas);
GlobalConfiguration.Configure(Config.AutofacConfig.Initialize);
}
}
public class TermsController : ApiController
{
public readonly ITermsService _termService;
public TermsController(ITermsService termService)
{
_termService = termService;
}
[HttpPost]
public HttpResponseMessage PostTerms()
{
string terms = "terms this is a new term inserted through fiddler";
if(terms != null)
{
bool created = _termService.UploadNewTerm(terms);
if (created)
{
var response = Request.CreateResponse(HttpStatusCode.Created);
return response;
}
else
return Request.CreateResponse(HttpStatusCode.InternalServerError);
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
}
Error:
ExceptionMessage=None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder'

In the constructor of EntityRepository<T> you inject CirclesDBEntities, but you register it as DbContext. So you can fix this by injecting DbContext to the constructor, changing your registration by removing .As<DbContext>() part of your registration or by adding .AsSelf() to your registration.

Related

Unable to cast object of type 'System.Linq.EnumerableQuery to type 'Microsoft.Azure.Documents.Linq.IDocumentQuery

I have a class with the following Method and am using Moq as a Unit Testing Framework. How can I mock the following:
FeedOptions feedOptions = new FeedOptions
{
MaxItemCount = 1000
};
var query = await _storeAccessClient.CreateDocumentQueryAsync<CustomEntity>(_collectionLink, feedOptions)
.Where(c => c.DataType == _dataType)
.OrderBy(c => c.StartTime, sortOrder)
.AsDocumentQuery()
.ExecuteNextAsync<CustomEntity>();
List<CustomEntity> result = query.ToList<CustomEntity>();
Any Help is greatly Appreciated !!
All you have to do is create a wrapper around EnumerableQuery class which inherits from IQueryable and IDocumentQuery like this:
internal class MockEnumerableQuery : IDocumentQuery<JTokenEx>, IOrderedQueryable<JTokenEx>
{
public IQueryable<JTokenEx> List;
private readonly bool bypassExpressions;
public MockEnumerableQuery(EnumerableQuery<JTokenEx> List, bool bypassExpressions = true)
{
this.List = List;
this.bypassExpressions = bypassExpressions;
}
public IEnumerator<JTokenEx> GetEnumerator()
{
return List.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public Expression Expression => List.Expression;
public Type ElementType => typeof(JTokenEx);
public IQueryProvider Provider => new MockQueryProvider(this, bypassExpressions);
public void Dispose()
{
}
public Task<FeedResponse<TResult>> ExecuteNextAsync<TResult>(CancellationToken token = new CancellationToken())
{
BindingFlags flags = BindingFlags.NonPublic | BindingFlags.Instance;
FeedResponse<JToken> feed = Activator.CreateInstance(typeof(FeedResponse<JToken>),
flags,null,new Object[] { List.Select(j => (JToken) j), 0, new NameValueCollection(), false, null}, null)
as FeedResponse<JToken>;
return Task.FromResult(feed as FeedResponse<TResult>);
}
public Task<FeedResponse<dynamic>> ExecuteNextAsync(CancellationToken token = new CancellationToken())
{
throw new NotImplementedException();
}
public bool HasMoreResults { get; }
}
class MockQueryProvider : IQueryProvider
{
private readonly MockEnumerableQuery mockQuery;
private readonly bool bypassExpressions;
public MockQueryProvider(MockEnumerableQuery mockQuery, bool byPassExpressions)
{
this.mockQuery = mockQuery;
this.bypassExpressions = byPassExpressions;
}
public IQueryable CreateQuery(Expression expression)
{
throw new NotImplementedException();
}
public IQueryable<TElement> CreateQuery<TElement>(Expression expression)
{
if (!bypassExpressions)
{
mockQuery.List = mockQuery.List.Provider.CreateQuery<TElement>(expression) as IQueryable<JTokenEx>;
}
return (IQueryable<TElement>)mockQuery;
}
public object Execute(Expression expression)
{
throw new NotImplementedException();
}
public TResult Execute<TResult>(Expression expression)
{
throw new NotImplementedException();
}
}
Now where your mock is returning EnumerableQuery, you return this MockEnumerableQuery class and you should be good.

Linq executing query generates not supported exception

I'm trying to execute a linq query in an extension method but I am getting the following exception on the ToArray() function call - it seems the query is having issues with my IList somehow, I have tried many different things and googled but fails to see the issue
An exception of type 'System.NotSupportedException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
Additional information: Cannot compare elements of type 'System.Collections.Generic.IList`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'. Only primitive types, enumeration types and entity types are supported.
Code
public static IList<Shared.Poco.DimValue> ToDimValuePocoList(this IQueryable<DAL.DimValue> source)
{
IList<Shared.Poco.DimValue> values = new List<Shared.Poco.DimValue>();
foreach (DAL.DimValue dv in source.ToArray())
{
values.Add(new Shared.Poco.DimValue
{
DimensionId = dv.DimensionID,
DimValueName = dv.DimValueName,
DimValueNo = dv.DimValueNo
});
}
return values;
}
The class the calls the extension looks like this:
public class DimValue : IDimValue
{
private IDimValueRepository _repository;
private IAccessableDimensionValues _accessableDimensionValues;
private IRevision _revision;
public DimValue(IDimValueRepository reposotory, IAccessableDimensionValues accessableDimensionValues, IRevision revision)
{
_repository = reposotory;
_accessableDimensionValues = accessableDimensionValues;
_revision = revision;
}
public IList<Shared.Poco.DimValue> GetDimValueList(int budgetId, Shared.Poco.Dimension dimension, IList<string> dimensionValues, Shared.Poco.User user)
{
IList<Shared.Poco.DimValue> values = new List<Shared.Poco.DimValue>();
int budgetRevisionId = _revision.GetLatesRevision(budgetId);
IList<string> uniqueAccessableUBLValues = _accessableDimensionValues.GetUniqueAccessableDimensionValues(dimension, user.UserId, budgetRevisionId);
if (dimensionValues != null && dimensionValues.Count > 0)
{
uniqueAccessableUBLValues = dimensionValues;
}
return _repository.GetDimValueList(budgetId, dimension.ToString(), uniqueAccessableUBLValues, user).ToDimValuePocoList();
}
The implementation of the injected repository class inherits from the following base repository class
public interface IRepository<T>
{
void Insert(T entity);
void Delete(T entity);
IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate);
IQueryable<T> GetAll();
T GetById(int id);
}
public class Repository<T> : IRepository<T> where T : class
{
protected DbSet<T> DbSet;
public Repository(DbContext dataContext)
{
DbSet = dataContext.Set<T>();
}
#region IRepository<T> Members
public void Insert(T entity)
{
DbSet.Add(entity);
}
public void Delete(T entity)
{
DbSet.Remove(entity);
}
public IQueryable<T> SearchFor(Expression<Func<T, bool>> predicate)
{
return DbSet.Where(predicate);
}
public IQueryable<T> GetAll()
{
return DbSet;
}
public T GetById(int id)
{
return DbSet.Find(id);
}
#endregion
}
Repository implementation
public class DimValueRepository : Repository<DimValue>, IDimValueRepository
{
public DimValueRepository(KonstruktEntities context) : base(context) { }
public IQueryable<DimValue> GetDimValueList(int budgetId, string dimensionId, IList<string> dimensionFilter, Shared.Poco.User user)
{
return this.SearchFor(dv => dv.BudgetID == budgetId && dv.DimensionID == dimensionId &&
(dimensionFilter == null || dimensionFilter.Count == 0 || dimensionFilter.Contains(dv.DimValueNo)));
}
public IQueryable<DimValue> GetDimValueList(Shared.Poco.Dimension dimension, string startsWith, Shared.Poco.User user)
{
return this.SearchFor(dv=>dv.DimensionID == dimension.ToString() &&
dv.DimValueNo.StartsWith(startsWith));
}
}
EDIT
It's failing on the following row in the ToDimValuePocoList function:
foreach (DAL.DimValue dv in source.ToArray())
Here is the row calling the extension in the DimValue class
return _repository.GetDimValueList(budgetId, dimension.ToString(), uniqueAccessableUBLValues, user).ToDimValuePocoList();
Answered by #Will in the comment above, i.e. cannot use dimensionFilter in my predicate. So I moved that logic outside of the predicate.

EF 6 - Ninject - The operation cannot be completed because the dbcontext has been disposed

I've seen a lot of questions with this error, so sorry for asking again, but no solutions have worked for me so far.
I'm working on a ASP.NET Web API project that's using the Ninject and Ninject.Web.Common references, where a DbContext is injected into the repositories. This error pops up the second time I send a request subsequently.
My stack trace :
at System.Data.Entity.Internal.InternalContext.CheckContextNotDisposed()
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.LazyInternalContext.get_ObjectContext()
at System.Data.Entity.Internal.InternalContext.DetectChanges(Boolean force)
at System.Data.Entity.Internal.InternalContext.GetStateEntries(Func`2 predicate)
at System.Data.Entity.Internal.InternalContext.GetStateEntries()
at System.Data.Entity.Infrastructure.DbChangeTracker.Entries()
at Project.Data.UnitOfWork.Commit() in c:\Projects\Project\src\DotNet\Project.Data\UnitOfWork.cs:line 22
at Project.Api.Infrastructure.UnitOfWorkAttribute.OnActionExecuted(HttpActionExecutedContext actionExecutedContext) in c:\Projects\Project\src\DotNet\Project.Api\Infrastructure\UnitOfWorkAttribute.cs:line 25
at System.Web.Http.Filters.ActionFilterAttribute.<CallOnActionExecutedAsync>d__1.MoveNext()
Ninject : RegisterServices
kernel.Bind<DataContextFactory>().ToSelf().InRequestScope().WithConstructorArgument("nameOrConnectionString", "Project");
kernel.Bind<DataContext>().ToMethod(context => kernel.Get<DataContextFactory>().GetContext()).InRequestScope();
kernel.Bind<IRepository<Device>>().To<Repository<Device>>();
kernel.Bind<IRepository<Person>>().To<Repository<Person>>();
kernel.Bind<UnitOfWork>().ToSelf().InRequestScope();
kernel.BindHttpFilter<UnitOfWorkAttribute>(FilterScope.Controller).WhenControllerType<DeviceController>();
kernel.BindHttpFilter<UnitOfWorkAttribute>(FilterScope.Controller).WhenControllerType<PersonController>();
My IRepositiry class
public interface IRepository<TAggregateRoot> where TAggregateRoot : class, IAggregateRoot
{
void Save(TAggregateRoot instance);
void Remove(TAggregateRoot instance);
TAggregateRoot One(Expression<Func<TAggregateRoot, bool>> predicate = null, params Expression<Func<TAggregateRoot, object>>[] includes);
IQueryable<TAggregateRoot> All(Expression<Func<TAggregateRoot, bool>> predicate = null, params Expression<Func<TAggregateRoot, object>>[] includes);
bool Exists(Expression<Func<TAggregateRoot, bool>> predicate = null);
int Count(Expression<Func<TAggregateRoot, bool>> predicate = null);
}
My person controller class
public class PersonController : ApiController
{
private readonly IRepository<Person> _personRepository;
public PersonController(IRepository<Person> personRepository)
{
_personRepository = personRepository;
}
...
}
My DbContext
private readonly IDictionary _configurations;
public DataContext(string nameOrConnectionString, IDictionary<MethodInfo, object> configurations)
: base(nameOrConnectionString)
{
_configurations = configurations;
}
public virtual void MarkAsModified<TEntity>(TEntity instance) where TEntity : class
{
Entry(instance).State = EntityState.Modified;
}
public virtual IDbSet<TEntity> CreateSet<TEntity>() where TEntity : class
{
return Set<TEntity>();
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
if (modelBuilder == null)
{
throw new ArgumentNullException("modelBuilder");
}
foreach (var config in _configurations)
{
config.Key.Invoke(modelBuilder.Configurations, new[] { config.Value });
}
base.OnModelCreating(modelBuilder);
}

Factory Pattern: Enum Parameter vs Explicit Method Name?

Say you have a factory that returns instances of ILightBulb. Two ways (there may be more) of implementing the factory are as follows:
Option 1 - Passing in an enum type
enum LightBulbType
{
Incandescent,
Halogen,
Led,
}
class ILightBulbFactory
{
public ILightBulb Create(LightBulbType type)
{
switch (type)
{
case LightBulbType.Incandescent:
return new IncandescentBulb();
case LightBulbType.Halogen:
return new HalogenBulb();
case LightBulbType.Led:
return new LedBulb();
}
}
}
Option 2 - Explicit method names
class ILightBulbFactory
{
public ILightBulb CreateIncandescent()
{
return new IncandescentBulb();
}
public ILightBulb CreateHalogen()
{
return new HalogenBulb();
}
public ILightBulb CreateLed()
{
return new LedBulb();
}
}
Which method is most preferable, and why?
Thanks.
In java, you can solve it in the enum, thus making sure that if you add new enums, all your code will remain working, instead of forgetting to add statements to your case.
enum LightBulbType
{
Incandescent{
#Override
public ILightBulb getInstance() {
return new IncandescentBulb();
}
},
Halogen{
#Override
public ILightBulb getInstance() {
return new HalogenBulb();
}
},
Led{
#Override
public ILightBulb getInstance() {
return new LedBulb();
}
};
public abstract ILightBulb getInstance();
}
class ILightBulbFactory
{
public ILightBulb Create(LightBulbType type)
{
return type.getInstance();
}
}
The equivalent for c# would be
public sealed class LightBulbType
{
public static readonly LightBulbType Incandescent = new
LightBulbType("Incandescent", new IncandescentBulb());
public static readonly LightBulbType Halogen = new
LightBulbType("Halogen", new HalogenBulb());
public static readonly LightBulbType LedBulb = new LightBulbType("Led",
new LedBulb());
public static IEnumerable<LightBulbType> Values
{
get
{
yield return Incandescent;
yield return Halogen;
yield return LedBulb;
}
}
private string Name { get; set; }
private ILightBulb Instance { get;}
private LightBulbType(string name, ILightBulb instance)
{
this.Name = name;
this.Instance = instance;
}
public override string ToString() => Name;
public ILightBulb GetInstance()
{
return Instance;
}
}
public interface ILightBulb
{
}
public class IncandescentBulb : ILightBulb
{
}
public class HalogenBulb : ILightBulb
{
}
public class LedBulb : ILightBulb
{
}
public static class LightBulbFactory
{
public static ILightBulb Create(LightBulbType type)
{
return type.GetInstance();
}
}
For call
ILightBulb halogenBulb = new HalogenBulb();
ILightBulb incandescentBulb = new IncandescentBulb();
ILightBulb ledBulb = new LedBulb();
or
ILightBulb halo = LightBulbFactory.Create(LightBulbType.Halogen);
ILightBulb inca = LightBulbFactory.Create(LightBulbType.Incandescent);
ILightBulb led = LightBulbFactory.Create(LightBulbType.LedBulb);

Do I need a Repository Class if I have a Service class and IRepository?

After reading, this question. I figured I need to look over my structure to avoid redundant code.
My current structure is Controller -> Repository -> IRepository.
The repository looks like this:
public class UserRepository : IUserRepository, IDisposable
{
private StudentSchedulingEntities _context;
public UserRepository(StudentSchedulingEntities context)
{
if (context == null)
throw new ArgumentNullException("context");
_context = context;
}
public IEnumerable<User> GetUsers()
{
return _context.Users.ToList();
}
public User GetUserByID(int id)
{
return _context.Users.Find(id);
}
public void InsertStudent(User user)
{
_context.Users.Add(user);
}
public void DeleteStudent(int userID)
{
User usr = _context.Users.Find(userID);
_context.Users.Remove(usr);
}
public void UpdateStudent(User user)
{
_context.Entry(user).State = EntityState.Modified;
}
public void Save() {
_context.SaveChanges();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_context != null)
{
_context.Dispose();
_context = null;
}
}
}
}
My IRepository looks like this:
public interface IUserRepository : IDisposable
{
IEnumerable<User> GetUsers();
User GetUserByID(int userID);
void InsertStudent(User user);
void DeleteStudent(int userID);
void UpdateStudent(User user);
void Save();
}
I want to avoid doing this again in the service layer. Do I need the Repository Class or should I just implement the Service Layer in replacement of the Repository?
Your service layer won't need any repository implementations, it will simply use a repository to lookup a user, add/edit/delete a user, etc.
Now, if I can offer a bit of opinion, I'd recommend going with a generic repository. That way, if you need to make new repositories it is really simple. We use nopCommerce, and they use the following code:
public partial interface IRepository<T> where T : BaseEntity
{
T GetById(object id);
void Insert(T entity);
void Update(T entity);
void Delete(T entity);
IQueryable<T> Table { get; }
}
And since it use Entity Framework, this is the implementation:
/// <summary>
/// Entity Framework repository
/// </summary>
public partial class EfRepository<T> : IRepository<T> where T : BaseEntity
{
private readonly IDbContext _context;
private IDbSet<T> _entities;
/// <summary>
/// Ctor
/// </summary>
/// <param name="context">Object context</param>
public EfRepository(IDbContext context)
{
this._context = context;
}
public T GetById(object id)
{
return this.Entities.Find(id);
}
public void Insert(T entity)
{
try
{
if (entity == null)
throw new ArgumentNullException("entity");
this.Entities.Add(entity);
this._context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
var msg = string.Empty;
foreach (var validationErrors in dbEx.EntityValidationErrors)
foreach (var validationError in validationErrors.ValidationErrors)
msg += string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage) + Environment.NewLine;
var fail = new Exception(msg, dbEx);
//Debug.WriteLine(fail.Message, fail);
throw fail;
}
}
public void Update(T entity)
{
try
{
if (entity == null)
throw new ArgumentNullException("entity");
this._context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
var msg = string.Empty;
foreach (var validationErrors in dbEx.EntityValidationErrors)
foreach (var validationError in validationErrors.ValidationErrors)
msg += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
var fail = new Exception(msg, dbEx);
//Debug.WriteLine(fail.Message, fail);
throw fail;
}
}
public void Delete(T entity)
{
try
{
if (entity == null)
throw new ArgumentNullException("entity");
this.Entities.Remove(entity);
this._context.SaveChanges();
}
catch (DbEntityValidationException dbEx)
{
var msg = string.Empty;
foreach (var validationErrors in dbEx.EntityValidationErrors)
foreach (var validationError in validationErrors.ValidationErrors)
msg += Environment.NewLine + string.Format("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage);
var fail = new Exception(msg, dbEx);
//Debug.WriteLine(fail.Message, fail);
throw fail;
}
}
public virtual IQueryable<T> Table
{
get
{
return this.Entities;
}
}
private IDbSet<T> Entities
{
get
{
if (_entities == null)
_entities = _context.Set<T>();
return _entities;
}
}
//TODO implement IDisposable interface
}
Now it would be as simple as IRepository<User> or IRepository<Whatever>.
Definitely no to redundant code :-) When you say:
My current structure is Controller -> Repository ->
Is Controller inheriting from Repository? You don't want that either. The repository layer typically interfaces to storage (XML, database, file system, etc) and maps to repository friendly classes. Another layer manages the mapping of the repository layer to your native business/service classes.

Resources