I have a RepositoryBase class that does some basic operations on Entities which are derived from EntityBase.
public class RepositoryBase
{
private ApplicationDbContext _context;
public DbSet<EntityBase> DbSet;
public RepositoryBase(ApplicationDbContext context )
{
_context = context;
}
public List<EntityBase> List(int entityStatus)
{
return DbSet.Where(a => a.EntityStatusId == entityStatus).OrderBy(a => a.Name).ToList();
}
public EntityBase GetTeamDetails(int id)
{
return this.DbSet.FirstOrDefault(a => a.Id == id);
}
internal List<EntityBase> ListActive()
{
return DbSet.Where(a => a.EntityStatusId == (int)EntityStatus.Active).ToList();
}
internal List<EntityBase> ListTrashed()
{
return DbSet.Where(a => a.EntityStatusId == (int)EntityStatus.Trashed).ToList();
}
public void SaveProject(EntityBase item)
{
DbSet.Attach(item);
_context.Entry(item).State = EntityState.Modified;
_context.SaveChanges();
}
public List<EntityBase> ListArchived()
{
return DbSet.Where(a => a.EntityStatusId == (int)EntityStatus.Archived).ToList();
}
internal List<EntityBase> Search(string searchText)
{
return DbSet.Where(a => a.Name.Contains(searchText)).ToList();
}
public EntityBase New(EntityBase item)
{
DbSet.Add(item);
_context.SaveChanges();
return item;
}
}
The issue I am having is passing the DbSet to the base class. This is what I want to do:
public TeamRepository(ApplicationDbContext context) : base(context)
{
this.DbSet = (DbSet<EntityBase>)context.Teams;
}
However, this does not compile. It says it cannot cast from DbSet to DbSet even through Team is derived from EntityBase.
How do I make this cast?
you can make it generic this way:
public class BaseRepository<T> : IBaseRepository<T> where T : EntityBase
{
public BaseRepository(CustomDBContext context)
{
if (context == null)
{
throw new ArgumentNullException("context", "The given parameter cannot be null.");
}
this.Context = context;
}
protected ApplicationDbContext Context
{
get;
private set;
}
public T Get(int id)
{
return Context.Set<T>().Find(id);
}
.....
}
You can't do it like that. What you can do is:
this.DbSet = context.Set<EntityBase>();
Related
I am using ASP.NET Core Web API. I have these models:
public abstract class EntityBase
{
[Key]
public int Id { get; set; }
}
public class Mandate : EntityBase
{
public int? MerchantId { get; set; }
public DateTime DueDate { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
[ForeignKey("MerchantId")]
public virtual Merchant Merchant { get; set; }
}
Model: Mandate
ViewModel (Dto):
public class MandateGetDto
{
public int? MerchantId { get; set; }
public DateTime DueDate { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
IBaseRepository:
public interface IBaseRepository<T> where T : BaseEntity
{
Task<IEnumerable<T>> GetAll();
bool EntityExists(long id);
}
BaseRepository:
public class BaseRepository<T> : IBaseRepository<T> where T : AuditableBaseEntity
{
private readonly DDMDbContext _context;
private DbSet<T> _entities;
public BaseRepository(DDMDbContext context)
{
_context = context;
_entities = context.Set<T>();
}
public async Task<IEnumerable<T>> GetAll()
{
var list = await _entities.ToListAsync();
return list;
}
public bool EntityExists(long id)
{
return _entities.Any(x => x.Id == id);
}
}
EntityMapper:
public MandateGetDto FromMandateToMandateGetDto(Mandate mandate)
{
MandateGetDto mandateDto = new MandateGetDto();
mandateDto.MerchantId = mandate.MerchantId;
mandateDto.DueDate = mandate.DueDate;
mandateDto.StartDate = mandate.StartDate;
mandateDto.EndDate = mandate.EndDate;
return mandateDto;
}
UnitOfWork:
public class UnitOfWork : IUnitOfWork
{
private readonly DContext _context;
public UnitOfWork(DContext context)
{
_context = context;
}
#region Mandate
private readonly IBaseRepository<Mandate> _mandateRepository;
public IBaseRepository<Mandate> MandateRepository => _mandateRepository ?? new BaseRepository<Mandate>(_context);
# endregion
public void Dispose()
{
if (_context != null)
{
_context.Dispose();
}
}
}
Below is the code I have written for the Mandate service which retrieves all the records for the mandates.
MandateService:
public async Task<ResponsePagination<GenericPagination<MandateGetDto>>> GetAll(int page, int sizeByPage)
{
string nextRoute = null, previousRoute = null;
IEnumerable<Mandate> data = await _unitOfWork.MandateRepository.GetAll();
var mapper = new EntityMapper();
var mandatesDto = data.Select(m => mapper.FromMandateToMandateGetDto(m)).ToList();
GenericPagination<MandateGetDto> objGenericPagination = GenericPagination<MandateGetDto>.Create(mandatesDto, page, sizeByPage);
ResponsePagination<GenericPagination<MandateGetDto>> response = new ResponsePagination<GenericPagination<MandateGetDto>>(objGenericPagination);
response.CurrentPage = objGenericPagination.CurrentPage;
response.HasNextPage = objGenericPagination.HasNextPage;
response.HasPreviousPage = objGenericPagination.HasPreviousPage;
response.PageSize = objGenericPagination.PageSize;
response.TotalPages = objGenericPagination.TotalPages;
response.TotalRecords = objGenericPagination.TotalRecords;
response.Data = objGenericPagination;
if (response.HasNextPage)
{
nextRoute = $"/mandates?page={(page + 1)}";
response.NextPageUrl = _uriPaginationService.GetPaginationUri(page, nextRoute).ToString();
}
else
{
response.NextPageUrl = null;
}
if (response.HasPreviousPage)
{
previousRoute = $"/mandates?page={(page - 1)}";
response.PreviousPageUrl = _uriPaginationService.GetPaginationUri(page, previousRoute).ToString();
}
else
{
response.PreviousPageUrl = null;
}
return response;
}
public async Task<IEnumerable<Mandate>> GetMandates()
{
return await _unitOfWork.MandateRepository.GetAll();
}
startup.cs:
services.AddTransient<IMandateService, MandateService>();
Controller:
[Produces("application/json")]
[ApiController]
[ApiVersion("1.0")]
public class AdminController : ControllerBase
{
private readonly IMerchantService _merchantService;
private readonly DDMDbContext _context;
public AdminController(DDMDbContext context, IMerchantService merchantService)
{
_merchantService = merchantService;
_context = context;
}
[HttpGet("mandates")]
[Authorize]
public async Task<ResponsePagination<GenericPagination<MandateGetDto>>> GetAllMyMandates(int page, int sizeByPage)
{
return await _mandateService.GetAll(page, sizeByPage);
}
}
When I used POSTMAN for the Get Request, I got this response:
{
"current_page": 0,
"page_size": 0,
"total_pages": -2147483648,
"total_records": 1,
"has_next_page": false,
"has_previous_page": false,
"data": []
}
Data is blank while total record is 1.
How do I resolve this?
Thanks
You have not shown us the principal part of your code, which is the controller
Controller is the reason why your web API even works. So, if you have misconfigured something, it should be present in the controller first or then somewhere else.
Show us the code for the controller.
Edit
I am not sure if DbSet is appropriate for the usage, but using the context object works for me.
You should use
_context.MandateOrWhateverElseItIs.ToListAsync();
instead of using
_entities.ToListAsync();
Using the DbSet can be an issue, I recommend using the context. My application works fruitfully with context.
Edit
This is your code in BaseRepository
public class BaseRepository<T> : IBaseRepository<T> where T : AuditableBaseEntity
{
private readonly DDMDbContext _context;
private DbSet<T> _entities;
public BaseRepository(DDMDbContext context)
{
_context = context;
_entities = context.Set<T>();
}
public async Task<IEnumerable<T>> GetAll()
{
var list = await _entities.ToListAsync();
return list;
}
public bool EntityExists(long id)
{
return _entities.Any(x => x.Id == id);
}
}
What you should change it to is
public class BaseRepository<T> : IBaseRepository<T> where T : AuditableBaseEntity
{
private readonly DDMDbContext _context;
private DbSet<T> _entities;
public BaseRepository(DDMDbContext context)
{
_context = context;
_entities = context.Set<T>();
}
public async Task<IEnumerable<T>> GetAll()
{
//Changes are here
var list = await _context.EntitiesOrWhateverElseItIs.ToListAsync(); //I don't know what the option is, you can look it inside the autocomplete. Be sure to change EntitiesOrWhateverElseItIs with the option you see in autocomplete menu
return list;
}
public bool EntityExists(long id)
{
return _entities.Any(x => x.Id == id);
}
}
I currently have a method that allows me to generate an IEnumerable object for my dropdown list in my web app forms.
Example of current code :
//Name with Id
StateListDp = _db.States.ToDropdownList(c => c.Name, c => Convert.ToString(c.Id, CultureInfo.InvariantCulture));
//Description with Id
StatusesListDp = _db.Statuses.ToDropdownList(c => c.Description, c => Convert.ToString(c.Id, CultureInfo.InvariantCulture));
I've just implemented Repository Design Pattern.
I'm able to convert it over to this now :
StateListDp = unitOfWork.State.GetDropDownList().ToList();
StatusesListDp = unitOfWork.Status.GetDropDownList().ToList();
I've created the following support class (I've excluded the unitOfWork for now )
public class StatusRepository : Repository<Statuses>, IStatusRepository
{
private readonly TenDDbContext context;
public StatusRepository(TenDDbContext context): base(context)
{
this.context = context;
}
public IEnumerable<Statuses> GetAllActive()
{
return Find(x => x.IsActive == true);
}
public IEnumerable<SelectListItem> GetDropDownList()
{
return GetAllActive()
.ToDropdownList(c => c.Description, c => Convert.ToString(c.Id, CultureInfo.InvariantCulture));
}
}
public class StateRepository : Repository<States>, IStateRepository
{
private readonly TenDDbContext context;
public StateRepository(TenDDbContext context): base(context)
{
this.context = context;
}
public IEnumerable<States> FindAllActive(Expression<Func<States, bool>> predicate)
{
return Find(predicate).Where(x => x.IsActive == true);
}
public IEnumerable<States> GetAllActive()
{
return Find(x => x.IsActive == true);
}
public IEnumerable<SelectListItem> GetDropDownList()
{
return GetAllActive()
.ToDropdownList(c => c.Name, c => Convert.ToString(c.Id, CultureInfo.InvariantCulture));
}
}
public class Repository<TEntity> : IRepository<TEntity> where TEntity : class
{
private readonly TenDDbContext context;
public Repository(TenDDbContext context)
{
this.context = context;
}
public TEntity Add(TEntity entity)
{
return context.Set<TEntity>().Add(entity).Entity;
}
//public bool save(TEntity entity)
//{
// var test= Add(entity);
// test.
//}
public void AddRange(IEnumerable<TEntity> entities)
{
context.Set<TEntity>().AddRange(entities);
}
public IEnumerable<TEntity> Find(Expression<Func<TEntity, bool>> predicate)
{
return context.Set<TEntity>().Where(predicate);
}
public TEntity SingleOrDefault(Expression<Func<TEntity, bool>> predicate)
{
return context.Set<TEntity>().SingleOrDefault(predicate);
}
public TEntity Get(int id)
{
return context.Set<TEntity>().Find(id);
}
public IEnumerable<TEntity> GetAll()
{
return context.Set<TEntity>().ToList();
}
public TEntity Update(TEntity entity)
{
//context.Attach(entity).State = EntityState.Modified;
// context.Attach(entity);
//return context.Entry(entity).State = EntityState.Modified;
return context.Update(entity)
.Entity;
}
public void Remove(TEntity entity)
{
context.Set<TEntity>().Remove(entity);
}
public void RemoveRange(IEnumerable<TEntity> entities)
{
context.Set<TEntity>().RemoveRange(entities);
}
}
So my issue is that I have 10 or so tables that I will need to retrieve this very similar data from.
I'm wondering there is a way to make the GetDropDownList a generic method?
So that I can limit the amount of repeat code ...
I'm even willing to make it two methods
GetDropDownNameList and GetDropDownDescriptionList
adding dropdownextension method
public static IEnumerable<SelectListItem> ToDropdownList<T>(this IEnumerable<T> items,
Func<T, string> text, Func<T, string> value = null, Func<T, Boolean> selected = null)
{
var listData = items.Select(p => new SelectListItem
{
Text = text.Invoke(p),
Value = (value == null ? text.Invoke(p) : value.Invoke(p)),
Selected = selected != null && selected.Invoke(p)
});
var defaultRow = new SelectListItem() { Value = "0", Text = "Please Select One", Selected = V };
var newList = listData.Prepend(defaultRow);
//return new SelectList(newList, "Value", "Text");
return newList;
}
passing the selection of the props for description and key should do the trick. If you want to make it even more generic to be inside the IRepository, replace GetAllActive() with a filter
public IEnumerable<SelectListItem> GetDropDownList(Expression<Func<TEntity, string>> predicateDescription, Expression<Func<TEntity, string>> predicateKey)
{
return GetAllActive().ToDropdownList(predicateDescription, predicateKey);
}
Using Unit, I'm trying to setup a test where I can delete an entry from my Mock list in order to test out the implementation in my CustomerManager.
My Repository:
public class Repository<T> : IRepository<T> where T : ModelBase
{
private readonly CustomerDbContext _context;
public Repository(CustomerDbContext context)
{
if (_context == null)
throw new ArgumentNullException(nameof(context));
_context = context;
}
public async Task Delete(int id, bool softDelete = true)
{
var entity = await GetById(id);
if (entity == null) return;
if (softDelete)
{
entity.IsDeleted = true;
Save(entity);
}
else
_context.Set<T>().Remove(entity);
}
public async Task<T> GetById(int id)
{
return await _context.Set<T>().FirstOrDefaultAsync(t => t.Id == id).ConfigureAwait(false);
}
public void Save(T entity)
{
if (entity.Id == 0)
_context.Set<T>().Add(entity);
else
_context.Entry(entity).State = EntityState.Modified;
}
}
My Unit Of Work is:
public class CustomerUnitOfWork : IUnitOfWork
{
public CustomerDbContext Context { get; }
public async Task<int> Commit()
{
foreach(var item in Context.ChangeTracker.Entries().Where(e => e.State == EntityState.Added || e.State == EntityState.Modified))
{
if (!(item.Entity is ModelBase entity))
continue;
if (item.State == EntityState.Added)
{
entity.CreatedDate = DateTime.UtcNow;
}
entity.ModifiedDate = DateTime.UtcNow;
}
return await Context.SaveChangesAsync();
}
}
My Manager is:
public class CustomerManager : ICustomerManager
{
private readonly IRepository<Models.Customer> _customerRepository;
protected readonly IUnitOfWork _unitOfWork;
public CustomerManager(IRepository<Models.Customer> customerRepository, IUnitOfWork unitOfWork)
{
_customerRepository = customerRepository;
_unitOfWork = unitOfWork ?? throw new ArgumentNullException(nameof(unitOfWork));
}
public async Task<int> Delete(int id, bool softDelete = true)
{
await _customerRepository.Delete(id, softDelete);
return await _unitOfWork.Commit();
}
public async Task<Models.Customer> GetById(int id)
{
return await _customerRepository.GetById(id);
}
}
In my Unit Test, I'm setting up the constructor like this:
private ICustomerManager MockManager;
private Mock<IUnitOfWork> UnitOfWork;
private List<Models.Customer> Customers;
Mock<IRepository<Models.Customer>> MockRepository;
public CustomerTest()
{
MockRepository = new Mock<IRepository<Models.Customer>>();
UnitOfWork = new Mock<IUnitOfWork>();
Customers = new List<Models.Customer>()
{
new Models.Customer
{
Id = 1,
Name = "Foo",
City = "Baltimore",
Company = "Foo Company"
},
new Models.Customer
{
Id = 2,
Name = "Bar",
City = "Owings Mills",
Company = "Bar Company"
}
};
MockRepository.Setup(repo => repo.GetAll()).ReturnsAsync(Customers);
MockRepository.Setup(repo => repo.GetById(It.IsAny<int>())).ReturnsAsync((int i) => Customers.SingleOrDefault(c => c.Id == i));
MockRepository.SetupAllProperties();
MockManager = new CustomerManager(MockRepository.Object, UnitOfWork.Object);
}
In my test method, I want to remove the first object in my test list.
public async Task ShouldDelete()
{
var countBeforeDelete = Customers.Count();
var countAfterDelete = await MockManager.Delete(1, true);
Assert.Equal(countBeforeDelete, countAfterDelete);
}
However, CountAfterDelete always returns 0. I'm not sure what I'm doing wrong.
Your Manager's Delete method returns await _unitOfWork.Commit();
By default, the Mock of IUnitOfWork will return default(int) which is 0.
I have a generic services which are calling generic repository. I need to manage unit test, but not able to do it. May you help me ?
public class EntityService<TEntity> : IEntityService<TEntity> where TEntity : class, new()
{
private readonly IRepositoryAsync<TEntity> _repository;
public EntityService(IRepositoryAsync<TEntity> repository)
{
_repository = repository;
}
public virtual IQueryable<TEntity> Entities => Queryable();
public virtual bool Delete(object id)
{
if (id == null)
throw new ArgumentNullException(nameof(id));
TEntity entity = _repository.Find(id);
if (entity != null)
return Delete(entity);
return false;
}
}
GENERIC REPOSITORY
public class Repository<TEntity> : IRepositoryAsync<TEntity> where TEntity : class, new()
{
private readonly IDataContextAsync _context;
private readonly DbSet<TEntity> _dbSet;
public Repository(IDataContextAsync context)
{
_context = context ?? throw new ArgumentNullException(nameof(context));
if (context is DbContext dbContext)
_dbSet = dbContext.Set<TEntity>();
}
public virtual void Delete(object id)
{
TEntity entity = _dbSet.Find(id);
Delete(entity);
}
}
What I tried is next:
I had create abstract generic test
public abstract class EntityServiceUnitTests<TEntity> where TEntity : class, IEntity,new()
{
private readonly IEntityService<TEntity> _service;
public EntityServiceUnitTests()
{
_service = CreateSystemUnderTest();
}
[Test]
[TestCase("299cd2b5-ab47-4006-9a47-c85e4770e9b1")]
public void Delete_EntityWithExistUniqueIdentifier_ReturnsTrue(Guid id)
{
bool response = _service.Delete(id);
Assert.True(response);
}
protected abstract IEntityService<TEntity> CreateSystemUnderTest();
}
Than I had implement concrete for unit test
public class ConcreteEntityServiceUnitTests : EntityServiceUnitTests<Data>
{
protected override IEntityService<Data> CreateSystemUnderTest()
{
MockBehavior behavior = MockBehavior.Strict;
Mock<IRepositoryAsync<Data>> repoMock = new Mock<IRepositoryAsync<Data>>(behavior);
repoMock.Setup(s => s.Queryable()).Returns(DataList().AsQueryable);
SetupService();
IEntityService<Data> entityService = new EntityService<Data>(repoMock.Object);
return entityService;
}
private void SetupService()
{
Mock<IEntityService<Data>> service = new Mock<IEntityService<Data>>();
service.Setup(s => s.Find(It.Is<Data>(f => f.Id == It.IsAny<Guid>()))).Returns(DataList().FirstOrDefault(w => w.Id == It.IsAny<Guid>()));
}
private IList<Data> DataList()
{
List<Data> dataList = new List<Data>();
dataList.Add(new Data
{
Id = new Guid("299cd2b5-ab47-4006-9a47-c85e4770e9b1"),
ObjectState = ObjectState.Added
});
dataList.Add(new Data
{
Id = new Guid("229cd2b5-ab47-4006-9a47-c85e4770e9b1"),
ObjectState = ObjectState.Added
});
return dataList;
}
}
As error I'm getting:
Moq.MockException :
IRepository<Data>.Find([299cd2b5-ab47-4006-9a47-c85e4770e9b1])
invocation failed with mock behavior Strict.
I know there are a few similar question out there regarding this issue with structure map, but my issue seems to not be resolvable with the solutions they needed. I must state I have used this same setup many times, but cannot see why this code is causing issues.
Here are all of the classes I think that are needed for help with troubleshooting my code.
ControllerConvention.cs
public class ControllerConvention : IRegistrationConvention
{
public void ScanTypes(TypeSet types, Registry registry)
{
foreach (Type type in types.AllTypes())
{
if (type.CanBeCastTo(typeof(Controller)) && !type.IsAbstract)
{
registry.For(type).LifecycleIs(new UniquePerRequestLifecycle());
}
}
}
}
IoC.cs
public static class IoC
{
public static IContainer Container { get; set; }
static IoC()
{
Container = new Container();
}
}
StandardRegistry.cs
public class StandardRegistry : Registry
{
public StandardRegistry()
{
Scan(scan =>
{
scan.TheCallingAssembly();
scan.Assembly("PotSmart.Service");
scan.Assembly("PotSmart.Data");
scan.WithDefaultConventions();
});
}
}
StructureMapDependencyResolver.cs
public class StructureMapDependencyResolver : IDependencyResolver
{
private readonly Func<IContainer> _factory;
public StructureMapDependencyResolver(Func<IContainer> factory)
{
_factory = factory;
}
public object GetService(Type serviceType)
{
if (serviceType == null)
{
return null;
}
var factory = _factory();
return serviceType.IsAbstract || serviceType.IsInterface
? factory.TryGetInstance(serviceType)
: factory.GetInstance(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _factory().GetAllInstances(serviceType).Cast<object>();
}
}
Global.asax
public IContainer Container
{
get
{
return (IContainer)HttpContext.Current.Items["_Container"];
}
set
{
HttpContext.Current.Items["_Container"] = value;
}
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
DependencyResolver.SetResolver(new StructureMapDependencyResolver(() => Container ?? IoC.Container));
IoC.Container.Configure(cfg =>
{
cfg.AddRegistry(new StandardRegistry());
cfg.AddRegistry(new ControllerRegistry());
});
}
Here are parts of my data and entities classes:
RepositoryBase.cs
public class RepositoryBase
{
private readonly PotSmartEntityModel1 _dataContext;
protected IDbFactory DbFactory { get; private set; }
protected PotSmartEntityModel1 DbContext
{
get
{
return _dataContext ?? DbFactory.Init();
}
}
protected RepositoryBase(IDbFactory dbFactory)
{
DbFactory = dbFactory;
var adapter = (IObjectContextAdapter)this;
var objectContext = adapter.ObjectContext;
// objectContext.CommandTimeout = 120; // value in seconds
}
}
public abstract class RepositoryBase<T> where T : class
{
private readonly PotSmartEntityModel1 _dataContext;
private readonly IDbSet<T> _dbSet;
protected IDbFactory DbFactory { get; private set; }
protected PotSmartEntityModel1 DbContext
{
get
{
return _dataContext ?? DbFactory.Init();
}
}
protected RepositoryBase(IDbFactory dbFactory)
{
DbFactory = dbFactory;
_dbSet = DbContext.Set<T>();
}
public virtual void Add(T entity)
{
_dbSet.Add(entity);
}
public virtual void Update(T entity)
{
_dbSet.Attach(entity);
DbContext.Entry(entity).State = EntityState.Modified;
}
public virtual void Delete(T entity)
{
_dbSet.Remove(entity);
}
public virtual void Delete(Expression<Func<T, bool>> where)
{
IEnumerable<T> objects = _dbSet.Where<T>(where);
foreach (T obj in objects)
{
_dbSet.Remove(obj);
}
}
public virtual T GetById(int id)
{
return _dbSet.Find(id);
}
public virtual T GetById(string id)
{
return _dbSet.Find(id);
}
public virtual IEnumerable<T> GetAll()
{
return _dbSet.ToList();
}
public virtual IEnumerable<T> GetMany(Expression<Func<T, bool>> where)
{
return _dbSet.Where(where).ToList();
}
public T Get(Expression<Func<T, bool>> where)
{
return _dbSet.Where(where).SingleOrDefault();
}
public virtual IQueryable<T> Query()
{
return _dbSet;
}
public virtual IQueryable<T> Query(Expression<Func<T, bool>> where)
{
return _dbSet.Where(where);
}
public virtual ObjectQuery<U> CreateQuery<U>(string query, ObjectParameter[] parameters)
{
return CastAsObjectContext().CreateQuery<U>(query, parameters);
}
public virtual ObjectQuery<U> CreateQuery<U>(string query)
{
return CreateQuery<U>(query, new ObjectParameter[0] { });
}
public virtual ObjectQuery<DbDataRecord> CreateQuery(string query, ObjectParameter[] parameters)
{
return CreateQuery<DbDataRecord>(query, parameters);
}
public virtual ObjectQuery<DbDataRecord> CreateQuery(string query)
{
return CreateQuery<DbDataRecord>(query);
}
private ObjectContext CastAsObjectContext()
{
var oContext = (DbContext as IObjectContextAdapter).ObjectContext;
return oContext;
}
}
DBFactory.cs
class DbFactory : Disposable, IDbFactory
{
private PotSmartEntityModel1 _dbContext;
public PotSmartEntityModel1 Init()
{
return _dbContext ?? (_dbContext = new PotSmartEntityModel1());
}
protected override void DisposeCore()
{
if (_dbContext != null)
{
_dbContext.Dispose();
}
}
}
IDBFactory.cs
public interface IDbFactory : IDisposable
{
PotSmartEntityModel1 Init();
}
IRepository.cs
public interface IRepository
{
}
public interface IRepository<T> where T : class
{
void Add(T entity);
void Update(T entity);
void Delete(T entity);
void Delete(Expression<Func<T, bool>> where);
T GetById(int id);
T GetById(string id);
IEnumerable<T> GetAll();
IEnumerable<T> GetMany(Expression<Func<T, bool>> where);
IQueryable<T> Query();
IQueryable<T> Query(Expression<Func<T, bool>> where);
ObjectQuery<U> CreateQuery<U>(string query, ObjectParameter[] parameters);
ObjectQuery<U> CreateQuery<U>(string query);
ObjectQuery<DbDataRecord> CreateQuery(string query, ObjectParameter[] parameters);
ObjectQuery<DbDataRecord> CreateQuery(string query);
}
Now, sorry for so much code but that way I get all the answer out there that some in the community may ask. The issue is on my controller, I use no default constructor and do the dependency injection like the following code show:
MarkerController.cs
public class MarkerController : Controller
{
private readonly IMarkerService _markerService;
public MarkerController(IMarkerService markerService)
{
_markerService = markerService;
}
// GET: Markers
public ActionResult Index()
{
return View();
}
}
When I run the code I keep getting the following error, and have tried anything I could think of.
StructureMap.StructureMapConfigurationException: 'No default Instance is registered and cannot be automatically determined for type 'PotSmart.Data.Interfaces.IDbFactory'
I know StructureMap does not always have the clearest error messages, but I feel this meant my Entity model was not being initialized at run time for some reason.It fails during "factory.GetInstance(serviceType)". Has anyone had this error, or does anyone see what I am obviously overlooking in the code sets I have above that would cause this issue? Thanks a million as always in advance.