Linq executing query generates not supported exception - linq

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.

Related

trino udf how to create a aggregate function for the window function

I tried to write a udf function to calculate my data. In the trino's docs, I knew I should to write a function plugin and I succeed to execute my udf aggregate function sql.
But when I write sql with aggregate function and window function, the sql executed failed.
The error log is com.google.common.util.concurrent.ExecutionError: java.lang.NoClassDefFoundError: com/example/ListState.
I think I may implement the interface about the window function.
The ListState.java file code
#AccumulatorStateMetadata(stateSerializerClass = ListStateSerializer.class, stateFactoryClass = ListStateFactory.class)
public interface ListState extends AccumulatorState {
List<String> getList();
void setList(List<String> value);
}
The ListStateSerializer file code
public class ListStateSerializer implements AccumulatorStateSerializer<ListState>
{
#Override
public Type getSerializedType() {
return VARCHAR;
}
#Override
public void serialize(ListState state, BlockBuilder out) {
if (state.getList() == null) {
out.appendNull();
return;
}
String value = String.join(",", state.getList());
VARCHAR.writeSlice(out, Slices.utf8Slice(value));
}
#Override
public void deserialize(Block block, int index, ListState state) {
String value = VARCHAR.getSlice(block, index).toStringUtf8();
List<String> list = Arrays.asList(value.split(","));
state.setList(list);
}
}
The ListStateFactory file code
public class ListStateFactory implements AccumulatorStateFactory<ListState> {
public static final class SingleListState implements ListState {
private List<String> list = new ArrayList<>();
#Override
public List<String> getList() {
return list;
}
#Override
public void setList(List<String> value) {
list = value;
}
#Override
public long getEstimatedSize() {
if (list == null) {
return 0;
}
return list.size();
}
}
public static class GroupedListState implements GroupedAccumulatorState, ListState {
private final ObjectBigArray<List<String>> container = new ObjectBigArray<>();
private long groupId;
#Override
public List<String> getList() {
return container.get(groupId);
}
#Override
public void setList(List<String> value) {
container.set(groupId, value);
}
#Override
public void setGroupId(long groupId) {
this.groupId = groupId;
if (this.getList() == null) {
this.setList(new ArrayList<String>());
}
}
#Override
public void ensureCapacity(long size) {
container.ensureCapacity(size);
}
#Override
public long getEstimatedSize() {
return container.sizeOf();
}
}
#Override
public ListState createSingleState() {
return new SingleListState();
}
#Override
public ListState createGroupedState() {
return new GroupedListState();
}
}
Thanks for help!!!!
And I found the WindowAccumulator class in the trino source code. But I don't know how to use it.
How to create a aggregate function for window function?

ASP.NET Web Api and Autofac IoC. Error: ExceptionMessage=None of the constructors found

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.

Ninject Interception in WebAPI and parameterless constructor failing

I have an MVC4 site that uses both MVC and WebAPI in it. All was going well till I tried to change my classes to have a cross cutting AOP class that would help with caching data. I am now finding that when I call a method that does not have the InterceptAttribute on it, it will crash because Ninject didn't inject with a parameter, and it fails.
My BLL class looks like this:
public class FooBLL
{
#region Private Variables
private readonly IDAL _context;
#endregion
#region Constructor
public Foo(IDAL context)
{
_context = context;
}
#endregion
#region Public Methods
public List<Bar> GetAllBars()
{
return _context.GetAllBars();
}
public List<Bar> GetTwoBars()
{
return _context.GetTwoBars();
}
#endregion
}
My WebApi Controller looks like this:
public class FooController : ApiController
{
#region Private Variables
private readonly FooBLL _fooBll;
#endregion
#region Constructor
public FooController(FooBLL fooBll)
{
_fooBll = fooBll;
}
#endregion
#region Public Methods
#region Estimate Types
#region Get
public List<Bar> GetAllBars()
{
return _fooBll.GetAllBars();
}
public List<Bar> GetTwoBars()
{
return _fooBll.GetTwoBars();
}
#endregion
#endregion
#endregion
}
In my Website, I created the following Ninject classes for resolving the controllers:
public class NinjectRegistrations : NinjectModule
{
public override void Load()
{
Kernel.Bind<IDAL>().To<DAL>().InSingletonScope();
}
}
public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver, System.Web.Mvc.IDependencyResolver
{
private readonly IKernel kernel;
public NinjectDependencyResolver(IKernel kernel)
: base(kernel)
{
this.kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(this.kernel.BeginBlock());
}
}
public class NinjectDependencyScope : IDependencyScope
{
private IResolutionRoot resolver;
internal NinjectDependencyScope(IResolutionRoot resolver)
{
Contract.Assert(resolver != null);
this.resolver = resolver;
}
public void Dispose()
{
var disposable = this.resolver as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
this.resolver = null;
}
public object GetService(Type serviceType)
{
if (this.resolver == null)
{
throw new ObjectDisposedException("this", "This scope has already been disposed");
}
return this.resolver.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
if (this.resolver == null)
{
throw new ObjectDisposedException("this", "This scope has already been disposed");
}
return this.resolver.GetAll(serviceType);
}
}
In Global.asax I then register this resolver:
NinjectHelper.Kernel = new StandardKernel(modules);
var ninjectResolver = new NinjectDependencyResolver(NinjectHelper.Kernel);
DependencyResolver.SetResolver(ninjectResolver); // MVC
GlobalConfiguration.Configuration.DependencyResolver = ninjectResolver; // Web API
//Register Filter Injector
GlobalConfiguration.Configuration.Services.Add(typeof(System.Web.Http.Filters.IFilterProvider), new NinjectWebApiFilterProvider(NinjectHelper.Kernel));
Things were fine till I added the attribute Cache using Ninject.Extensions.Interception.Attributes.InterceptAttribute.
The class now looks like this (note that I added a parameterless constructor and marked one of the methods as virtual, these are both required for the Interception to work):
public class FooBLL
{
#region Private Variables
private readonly IDAL _context;
#endregion
#region Constructor
public Foo(IDAL context)
{
_context = context;
}
public Foo()
{
}
#endregion
#region Public Methods
public List<Bar> GetAllBars()
{
return _context.GetAllBars();
}
[Cache(DefaultTimeoutMinutes = 20)]
public virtual List<Bar> GetTwoBars()
{
return _context.GetTwoBars();
}
#endregion
}
Now on the WebAPI controller, when I call GetToBars(the method with the Intercept Attribute), everything still works fine.
However, when I call GetAllBars(the method that doesn't have the Intercept Attribute), I fail with an exception that _context is null.
Any help would be greatly appreciated.
Ben

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);
}

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