DBContext.Set<T> does not contain definition of Set<T> - asp.net-mvc-3

I am trying to implement an abstract repository pattern as described in THIS post. I'm getting the error message
'C' does not contain a definition for 'Set' and no extension method
'Set' accepting a first argument of type 'C' could be found (are you
missing a using directive or an assembly reference?)
where C is the DBContext
namespace Rental.Data.Entity.Repository
{
public abstract class GenericRepo<C, T> :
IGenericRepo<T> where T : class where C : RentalContainer, new()
{
private C _DBContext = new C();
protected C DBContext
{
get { return _DBContext; }
set { _DBContext = value; }
}
public virtual IQueryable<T> GetAll()
{
IQueryable<T> query = _DBContext.Set<T>(); <-- here is gives the error
return query;
}
yet another update
public partial class RentalContainer : ObjectContext
{
#region Constructors
/// <summary>
/// Initializes a new RentalContainer object using the connection string found in the 'RentalContainer' section of the application configuration file.
/// </summary>
public RentalContainer() : base("name=RentalContainer", "RentalContainer")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
/// <summary>
/// Initialize a new RentalContainer object.
/// </summary>
public RentalContainer(string connectionString) : base(connectionString, "RentalContainer")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}

ObjectContext does not have a Set method. It has CreateObjectSet method
public abstract class GenericRepo<C, T> : IGenericRepo<T>
where T : class
where C : RentalContainer, new()
{
private C _DBContext = new C();
protected C DBContext
{
get { return _DBContext; }
set { _DBContext = value; }
}
public virtual IQueryable<T> GetAll()
{
IQueryable<T> query = _DBContext.CreateObjectSet<T>();
return query;
}
}

Add reference to EntityFramework.dll
http://msdn.microsoft.com/en-us/library/gg679544(v=vs.103).aspx

Press ctrl + . and use Microsoft.EntityFrameworkCore; I had to add. But I got this error when I accidentally created an empty class named DbContext.
The solution for me is to delete the empty DbContext class and add the correct using line to DbContext. (using Microsoft.EntityFrameworkCore;)

Make sure your DataContext class extends DBContext

Related

Com class not showing main interface

I have an interface and a class in the tyle ibrary that is produced the interface appears and so does the class but the class has no methods exposed on it. so I cannot create an Application object in say VBA in Microsoft Word and call the methods on it, does anyone know what is wrong?
[ComVisible(true), Guid("261D62BE-34A4-4E49-803E-CC3294613505")]
public interface IApplication
{
[DispId(207)]
[ComVisible(true)]
IExporter Exporter { get; }
[DispId(202)]
[ComVisible(true)]
object CreateEntity([In] kEntityType EntityType, [In] object aParent);
[DispId(208)]
[ComVisible(true)]
string GenerateSpoolFileSpec();
}
[ComVisible(true), Guid("BA7F4588-0B51-476B-A885-8E1436EA0768")]
public class Application : IApplication
{
protected Exporter FExporter;
public Application()
{
FExporter = new Exporter();
}
[DispId(207)]
[ComVisible(true)]
public IExporter Exporter
{
get {return FExporter;}
}
[DispId(202)]
[ComVisible(true)]
public object CreateEntity([In] kEntityType EntityType, [In] object aParent)
{
switch (EntityType)
{
case TypeJob:
return new Job(this, aParent);
case kappEntityType.kappEntityTypePage:
return new Page(this, aParent);
}
return null;
}
[DispId(208)]
[ComVisible(true)]
public string GenerateSpoolFileSpec()
{
string path = string.Format(JOB_PARAMS_PATH_SKELETON, SpoolFolder, DateTime.Now.ToString("yyyy.MM.dd.hh.mm.ss.fff"));
return path;
}
}
Got it, don’t let dotnet handle it for you on the interface put an interfacetype e.g.
[ComVisible(true), Guid("261D62BE-34A4-4E49-803E-CC3294613505"), InterfaceType(ComInterfaceType.InterfaceIsDual)]
On the class use a classinterface e.g
[ComVisible(true), Guid("BA7F4588-0B51-476B-A885-8E1436EA0768"), ClassInterface(ClassInterfaceType.None)]

Entity framework: ObjectContext and inheritance

I need to have a CRUd operations on my class (CompetenceSpecific).
Competence has three derived classes - CompetenceFunction, CompetenceArea and CompetenceSpecifc
The error I recieved:
There are no EntitySets defined for the specified entity type 'CompetencyManagement.Domain.Entities.CompetenceFunction'. If 'CompetencyManagement.Domain.Entities.CompetenceFunction' is a derived type, use the base type instead. Parameter name: TEntity
How should I correct this? Please suggest a solution that would solve my problem. Thanks
Please check the code below, I removed some parts of the code for simplicity.
--MODEL
public class Competence
{
public int CompetenceID { get; set; }
public int CourseID { get; set; }
...
}
public class CompetenceFunction : Competence
{
}
--REPOSITORY and interfaces
public interface IRepository<T> where T : class
{
T GetById(object id);
IEnumerable<T> GetAll();
IEnumerable<T> Query(Expression<Func<T, bool>> filter);
void Add(T entity);
void Remove(T entity);
}
public abstract class Repository<T> : IRepository<T>
where T : class
{
protected IObjectSet<T> _objectSet;
public Repository(ObjectContext context)
{
_objectSet = context.CreateObjectSet<T>();
}
...
}
public class CompetenceFunctionRepository : Repository<CompetenceFunction>
{
public CompetenceFunctionRepository(ObjectContext context)
: base(context)
{
}
public override CompetenceFunction GetById(object id)
{
return _objectSet.SingleOrDefault(s => s.CompetenceID == (int)id);
}
}
--UNIT oF WORK
public interface IUnitOfWork
{
IRepository<CompetenceFunction> CompetenceFunctions { get; }
IRepository<CompetenceArea> CompetenceAreas { get; }
IRepository<CompetenceSpecific> CompetenceSpecifics { get; }
void Commit();
}
public class UnitOfWork : IUnitOfWork, IDisposable
{
private CompetenceFunctionRepository _competencefunction;
private CompetenceAreaRepository _competencearea;
private CompetenceSpecificRepository _competencespecifc;
public UnitOfWork(ObjectContext context)
{
if (context == null)
{
throw new ArgumentNullException("Context was not supplied");
}
_context = context;
}
#region IUnitOfWork Members
public IRepository<CompetenceFunction> CompetenceFunctions
{
get
{
if (_competencefunction == null)
{
_competencefunction = new CompetenceFunctionRepository(_context);
}
return _competencefunction;
}
}
public IRepository<CompetenceArea> CompetenceAreas
{
get
{
if (_competencearea == null)
{
_competencearea = new CompetenceAreaRepository(_context);
}
return _competencearea;
}
}
public IRepository<CompetenceSpecific> CompetenceSpecifics
{
get
{
if (_competencespecifc == null)
{
_competencespecifc = new CompetenceSpecificRepository(_context);
}
return _competencespecifc;
}
}
--Im getting an error in this part of Repository
public Repository(ObjectContext context)
{
_objectSet = context.CreateObjectSet<T>();
}
There are no EntitySets defined for the specified entity type 'CompetencyManagement.Domain.Entities.CompetenceFunction'. If 'CompetencyManagement.Domain.Entities.CompetenceFunction' is a derived type, use the base type instead. Parameter name: TEntity
Here's how I implement in the controller
private IUnitOfWork _unitOfWork;
var a = _unitOfWork.CompetenceFunctions.GetAll();
return View(a);
You have to get derived type by the OfType function, e.g.
context.CreateObjectSet<Competence>().OfType<CompetenceFunction>()
In your case that would mean that there is only a CompetenceRepository that serves all derivatives of Competence.
Edit
(After your comment)
First, UoW is meant for temporarily storing changes that should be dealt with in one batch (like changes to be committed to the database). GetAll and similar functions are repository stuff.
But do you need repositories? I like this post. When beginning to know EF, I would focus on the ins and outs of EF without getting distracted too much by surrounding architecture. E.g. start with services that at the inside communicate directly with the context and expose methods like GetCompetenceFunctions, GetCompetenceAreas (using OfType), and SaveCompetenceFunction, ....
You can address these service methods directly from action methods in the MVC controllers.

How to test Singleton class that has a static dependency

I have a Singleton class that uses the thread-safe Singleton pattern from Jon Skeet as seen in the TekPub video. The class represents a cached list of reference data for dropdowns in an MVC 3 UI.
To get the list data the class calls a static method on a static class in my DAL.
Now I'm moving into testing an I want to implement an interface on my DAL class but obviously cannot because it is static and has only one static method so there's no interface to create. So I want to remove the static implementation so I can do the interface.
By doing so I can't call the method statically from the reference class and because the reference class is a singleton with a private ctor I can't inject the interface. How do I get around this? How do I get my interface into the reference class so that I can have DI and I can successfully test it with a mock?
Here is my DAL class in current form
public static class ListItemRepository {
public static List<ReferenceDTO> All() {
List<ReferenceDTO> fullList;
... /// populate list
return fullList;
}
}
This is what I want it to look like
public interface IListItemRepository {
List<ReferenceDTO> All();
}
public class ListItemRepository : IListItemRepository {
public List<ReferenceDTO> All() {
List<ReferenceDTO> fullList;
... /// populate list
return fullList;
}
}
And here is my singleton reference class, the call to the static method is in the CheckRefresh call
public sealed class ListItemReference {
private static readonly Lazy<ListItemReference> instance =
new Lazy<ListItemReference>(() => new ListItemReference(), true);
private const int RefreshInterval = 60;
private List<ReferenceDTO> cache;
private DateTime nextRefreshDate = DateTime.MinValue;
public static ListItemReference Instance {
get { return instance.Value; }
}
public List<SelectListDTO> SelectList {
get {
var lst = GetSelectList();
lst = ReferenceHelper.AddDefaultItemToList(lst);
return lst;
}
}
private ListItemReference() { }
public ReferenceDTO GetByID(int id) {
CheckRefresh();
return cache.Find(item => item.ID == id);
}
public void InvalidateCache() {
nextRefreshDate = DateTime.MinValue;
}
private List<SelectListDTO> GetSelectList() {
CheckRefresh();
var lst = new List<SelectListDTO>(cache.Count + 1);
cache.ForEach(item => lst.Add(new SelectListDTO { ID = item.ID, Name = item.Name }));
return lst;
}
private void CheckRefresh() {
if (DateTime.Now <= nextRefreshDate) return;
cache = ListItemRepository.All(); // Here is the call to the static class method
nextRefreshDate = DateTime.Now.AddSeconds(RefreshInterval);
}
}
}
You can use the singleton based on instance(not based on static), for which you can declare interface like this.
public interface IListItemRepository
{
List<ReferenceDTO> All();
}
public class ListItemRepository : IListItemRepository
{
static IListItemRepository _current = new ListItemRepository();
public static IListItemRepository Current
{
get { return _current; }
}
public static void SetCurrent(IListItemRepository listItemRepository)
{
_current = listItemRepository;
}
public List<ReferenceDTO> All()
{
.....
}
}
Now, you can mock IListItemRepository to test.
public void Test()
{
//arrange
//If Moq framework is used,
var expected = new List<ReferneceDTO>{new ReferneceDTO()};
var mock = new Mock<IListItemRepository>();
mock.Setup(x=>x.All()).Returns(expected);
ListItemRepository.SetCurrent(mock.Object);
//act
var result = ListItemRepository.Current.All();
//Assert
Assert.IsSame(expected, result);
}
Which DI framework are you using? Depending on your answer, IOC container should be able to handle single-instancing so that you don't have to implement your own singleton pattern in the caching class. In your code you would treat everything as instanced classes, but in your DI framework mappings you would be able to specify that only one instance of the cache class should ever be created.
One way to test it would be if you refactor your ListItemReference by adding extra property:
public sealed class ListItemReference {
...
public Func<List<ReferenceDTO>> References = () => ListItemRepository.All();
...
private void CheckRefresh() {
if (DateTime.Now <= nextRefreshDate) return;
cache = References();
nextRefreshDate = DateTime.Now.AddSeconds(RefreshInterval);
}
}
And then in your test you could do:
ListItemReference listReferences = new ListItemReference();
listReferences.References = () => new List<ReferenceDTO>(); //here you can return any mock data
Of course it's just temporary solution and I would recommend getting rid of statics by using IoC/DI.

Ninject UnitOfWork confusion

I use Ninject all the time with my MVC 3 applications, but I'm trying to change the Pattern for my Data Objects to use UnitOfWork and I'm having trouble figuring out how to get Ninject to handle this properly.
I know my implementation of classes work when they are constructed manually like this in my console application:
IDatabaseFactory factory = new DatabaseFactory();
IUnitOfWork worker = new UnitOfWork(factory);
IBlogCategoryDao dao = new BlogCategoryDao(factory);
IBlogCategoryService service = new BlogCategoryService(dao);
BlogCategory category = service.GetById(id);
try
{
if (category != null)
{
service.Delete(category);
worker.Commit();
Console.WriteLine("Category deleted successfully!");
}
else
{
Console.WriteLine("Entity doesn't exist.");
}
}
catch (Exception ex)
{
Console.WriteLine("Error deleting category: {0}", ex.Message);
}
In my MVC 3 application I'm using the Ninject.MVC3 NuGet package, and this is in the RegisterServices method.
private static void RegisterServices(IKernel kernel)
{
kernel.Bind<IDatabaseFactory>().To<DatabaseFactory>();
kernel.Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();
kernel.Bind<IBlogCategoryDao>().To<BlogCategoryDao>();
kernel.Bind<IBlogDao>().To<BlogDao>();
kernel.Bind<IBlogCategoryService>().To<BlogCategoryService>();
kernel.Bind<IBlogService>().To<BlogService>();
}
While this works for the most part, Get requests, all POST requests (Insert, Update, Delete) don't get executed. There is no exception thrown and when I step through it, it goes through the SaveChanges() method without a problem and returns back up the stack, but nothing is executed. So I know I must be missing something with my Ninject configuration.
Here's my Unit of Work class.
public class UnitOfWork : IUnitOfWork
{
private Database _database; <-- DbContext derived class
private readonly IDatabaseFactory _databaseFactory;
public UnitOfWork(IDatabaseFactory databaseFactory)
{
this._databaseFactory = databaseFactory;
}
public Database Database
{
get
{
return _database ?? (_database = _databaseFactory.Get());
}
}
public void Commit()
{
Database.Commit();
}
}
Here's the DatabaseFactory class:
public class DatabaseFactory : Disposable, IDatabaseFactory
{
private Database _database;
public DatabaseFactory()
{
}
public virtual Database Get()
{
if (_database == null)
{
_database = DataObjectFactory.CreateContext();
}
return _database;
}
protected override void DisposeCore()
{
if (_database != null)
{
_database.Dispose();
}
}
}
And my DataObjectFactory class:
public static class DataObjectFactory
{
private static readonly string _connectionString;
/// <summary>
/// Static constructor. Reads the connectionstring from web.config just once.
/// </summary>
static DataObjectFactory()
{
string connectionStringName = ConfigurationManager.AppSettings.Get("ConnectionStringName");
_connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
}
/// <summary>
/// Creates the Context using the current connectionstring.
/// </summary>
/// <remarks>
/// Gof pattern: Factory method.
/// </remarks>
/// <returns>Action Entities context.</returns>
public static Database CreateContext()
{
return new Database(_connectionString);
}
}
This is a similar pattern as used in the EFMVC CodePlex application, but I don't use AutoFac.
Any thoughts on this are appreciated.
Thanks.
I just do this:
kernel.Bind<IUnitOfWork>.To<EFUnitOfWork>().InRequestScope();
EFUnitOfWork.cs
public class EFUnitOfWork : DbContext, IUnitOfWork
{
// your normal DbContext plus your IUnitOfWork members that delegate to EF context
}
Since EF already implements a form of Unit Of Work, this allows you to use a more generic interface for it, and inject it easily.
Also, you can implement the EF constructors for connection strings and just pass them to base constructors. Then you can use the Ninject .WithConstructorArgument() to configure the connection string using your AppSettings code.

linq populate custom collection

I have a collection defined as:
public class MyCollection : List<MyItem>
{
...
}
public class MyItem
{
...
}
Using linq, I can use the Select method to return a IEnumerable, and I can call .ToList on that to get an IList but is there some way of getting back a type of MyCollection? Because I am tring to instantiate a class which has a property of type MyCollection, and I want to use object initialization.
For example:
public class MyClass
{
MyCollection TestCollection {get;set}
...
}
MyClass test = new MyClass()
{
...
TestCollection = SomeObject.Select(item => new MyItem()
{
...
}).ToList();
}
I get a compile error because ToList returns List and it can't cast to a MyCollection object. Is there a way to do that?
You'll need to construct your MyCollection instance with the IEnumerable<MyItem>. Add a constructor like:
public MyCollection(IEnumerable<MyItem> items) : base(items) {}
Then, when you go to use this, you can do:
TestCollection = new MyCollection(SomeObject.Select(item => new MyItem());
You could make your own extension method that builds your collection from an IEnumerable, like
public static class Extensions
{
public static MyCollection ToMyCollection(this IEnumerable<MyItem> items)
{
//build and return your collection
}
}
or if MyItem is a placeholder for generic types in your context :
public static class Extensions
{
public static MyCollection ToMyCollection<T>(this IEnumerable<T> items)
{
//build and return your collection
}
}
Just mimic ToList:
public static class MyCollectionExtensions {
public static MyCollection ToMyCollection(this IEnumerable<MyItem> source) {
if (source == null) throw new NullReferenceException();
return new MyCollection(source);
}
}
MyCollection needs a new constructor:
public class MyCollection : List<MyItem> {
public MyCollection() : base() { }
public MyCollection(IEnumerable<MyItem> source) : base(source) { }
...
}
Also, it's generally not advisable to expose a setter for a collection. You should encapsulate mutation of the collection inside the class:
public class MyClass {
public MyCollection TestCollection { get { ... } } // should return a read-only collection
public void Add(MyItem item) {
_testCollection.Add(item);
}
MyCollection _testCollection = ...;
...
}

Resources