i have this Dependency resolver
public class NinjectDependencyResolvercs : IDependencyResolver
{
private readonly IResolutionRoot resolutionRoot;
public NinjectDependencyResolvercs(IResolutionRoot kernel)
{
resolutionRoot = kernel;
}
public object GetService(Type serviceType)
{
return resolutionRoot.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return resolutionRoot.GetAll(serviceType);
}
}
in global.asax.cs
// Ninject DI container ----------------------------------------------------------- |
public void SetupDependencyInjection()
{
// Create Ninject DI kernel
IKernel kernel = new StandardKernel();
#region Register services with Ninject DI Container
// DbContext to SqlDataContext
kernel.Bind<DbContext>()
.To<SqlDataContext>();
// IRepository to SqlRepository
kernel.Bind<IRepository>()
.To<SqlRepository>();
// IUsersServices to UsersServices
kernel.Bind<IUsersServices>()
.To<UsersServices>();
// IMessagesServices to MessagesServices
kernel.Bind<IMessagesServices>()
.To<MessagesServices>();
// IJobAdvertsServices to JobAdvertsServices
kernel.Bind<IJobAdvertsServices>()
.To<JobAdvertsServices>();
#endregion
// Tell ASP.NET MVC 3 to use Ninject DI Container
DependencyResolver.SetResolver(new NinjectDependencyResolvercs(kernel));
}
// --------------------------------------------------------------------------------- |
and class
public class SqlDataContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Profile> Profiles { get; set; }
public DbSet<Role> Roles { get; set; }
public DbSet<JobAdvert> JobAdverts { get; set; }
public DbSet<Message> Messages { get; set; }
protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasMany(x => x.Roles).WithMany(x => x.Users).Map(x =>
{
x.MapLeftKey(y => y.UserId, "UserId");
x.MapRightKey(y => y.RoleId, "RoleId");
x.ToTable("UsersInRoles");
});
base.OnModelCreating(modelBuilder);
}
}
all dependecies work fine but for DbContext to SqlDataContext is problem. If use this:
public class SqlRepository
{
private DbContext dataContext;
public SqlRepository(DbContext dataContext) {
this.dataContext = dataContext;
}
public DbSet<User> Users {
get {
return dataContext.Users;
}
}
}
then
dataContext.Users
and all others properties alert this error:
'System.Data.Entity.DbContext' does not contain a definition for 'JobAdverts' and no extension method 'JobAdverts' accepting a first argument of type 'System.Data.Entity.DbContext' could be found (are you missing a using directive or an assembly reference?)
Have anyone any idea why DI doent work for Class DbContext ?
If I understand correctly, You're injecting DbContext which doesn't have those methods/properties, as they're declared in the derived type SqlDataContext.
You need to inject the SqlDataContext. If you want to use an interface, you'll need to extract an interface from SqlDataContext.
EDIT:
Ninject binds at runtime while the errors you're getting (I presume) are at compile time. You could get around this by using the dynamic key word, but that's just working AROUND the problem.
public class SqlRepository
{
private dynamic dataContext;
public SqlRepository(DbContext dataContext) {
this.dataContext = dataContext;
}
...
}
What you need to do is change the signature to use your SqlDataContext:
public class SqlRepository
{
private SqlDataContextdata Context;
public SqlRepository(SqlDataContextdata Context) {
this.dataContext = dataContext;
}
...
}
because DbContext does not contain those methods, only your SqlContext does. and your sqlcontext is bound to DbContext at runtime.
Related
I have a CatalogDbContext class.
I want to use Bogus library to seed fake data into the database that my unit tests will use.
The example provided in bogus's github repo makes use of the HasData method of the CatalogDbContext class to seed data into the tables.
However, I will not want this HasData method to be executed from the API - meaning, the HasData method should only be run if the DBContext is created from the Unit Tests.
Kindly advise how to achieve this?.
using Bogus;
using Catalog.Api.Database.Entities;
using Microsoft.EntityFrameworkCore;
namespace Catalog.Api.Database
{
public class CatalogDbContext : DbContext
{
public CatalogDbContext(DbContextOptions<CatalogDbContext> options) : base(options)
{
}
public DbSet<CatalogItem> CatalogItems { get; set; }
public DbSet<CatalogBrand> CatalogBrands { get; set; }
public DbSet<CatalogType> CatalogTypes { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.ApplyConfiguration(new CatalogBrandEntityTypeConfiguration());
builder.ApplyConfiguration(new CatalogTypeEntityTypeConfiguration());
builder.ApplyConfiguration(new CatalogItemEntityTypeConfiguration());
FakeData.Init(10);
builder.Entity<CatalogItem>().HasData(FakeData.CatalogItems);
}
}
internal class FakeData
{
public static List<CatalogItem> CatalogItems = new List<CatalogItem>();
public static void Init(int count)
{
var id = 1;
var catalogItemFaker = new Faker<CatalogItem>()
.RuleFor(ci => ci.Id, _ => id++)
.RuleFor(ci => ci.Name, f => f.Commerce.ProductName());
}
}
}
I m new in .net core 2.1
I m working with .net core 2.1 with code first approach
issue is when I create a new object dbcontext class then give error see below line
dbcontextstudent db=new dbcontextstudent(); //here give an red line
appsettings.json
},
"ConnectionStrings": {
"sqlserverconn": "Server=DEVISSHAHID; Database=studdbs; User id=xxxx;Password=xxxxx;"
},
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
//connection string
services.AddDbContext<DbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("sqlserverconn")));
student.cs
namespace WebApplication1.Models
{
public class student
{
[Key]
public int studid { get; set; }
public string studname { get; set; }
public string studsalary { get; set; }
public int studage { get; set; }
}
}
dbcontextstudent.cs
namespace WebApplication1.Models
{
public class dbcontextstudent : DbContext
{
public dbcontextstudent(DbContextOptions<dbcontextstudent> options) : base(options)
{
}
public DbSet<student> stud { get; set; }
}
}
HomeController.cs
I m not understood the above intellisense
I write the code as per intellisense but still give an error I know error is clear but not solved
which place doing I m wrong?
You will have to pass your DbContext type to the AddDbContext method in ConfigureServices method like this:
services.AddDbContext<dbcontextstudent>(options => options.UseSqlServer(Configuration.GetConnectionString("sqlserverconn")));
After that, you have registered the dbcontextstudent class in dependency injection.
You shouldn't create the instance of dbcontextstudent on your own like you did:
dbcontextstudent db=new dbcontextstudent();
Instead you can inject it though the constructor of your controller like this:
public HomeController : Controller
{
private readonly dbcontextstudent _db;
public HomeController(dbcontextstudent db)
{
_db = db;
}
... and then you can use the _db variable in your post action
}
I try to write an MVC n tier application. I have used repository pattern during connecting to the database. In my repository class, I have a Context variable inside repository class. I am not sure that this approach is true. Here are my codes:
public class TTPDbContext : DbContext
{
public TTPDbContext() : base("TTPContext")
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<TTPDbContext>());
Database.Log = s => Debug.WriteLine(s);
Configuration.AutoDetectChangesEnabled = true;
}
public DbSet<Kisi> Kisiler { get; set; }
public DbSet<BakanlikBirim> BakanlikBirimleri { get; set; }
public DbSet<DisBirim> DisBirimler { get; set; }
public DbSet<Kullanici> Kullanicilar { get; set; }
public DbSet<Talep> Talepler { get; set; }
public DbSet<UnvanPozisyon> UnvanPozisyonlar { get; set; }
public DbSet<TalepDurum> TalepDurumlar { get; set; }
public DbSet<TalepKagidi> TalepKagidi { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("OsiTtp");
}
}
Here is the repository class:
public class TTPRepository : ITTPRepository,IDisposable
{
private IErrorHandling _errorHandling;
private TTPDbContext _context;
public TTPRepository()
{
this._errorHandling = new ErrorHandling();
this._context = new TTPDbContext();
}
// other sections has been dismissed for brevity.
public List<DisBirim> GetAllExternalInstitutions()
{
List<DisBirim> result = null;
DbSet<DisBirim> intermediaryresult = null;
try
{
result = new List<DisBirim>();
intermediaryresult = this._context.DisBirimler;
if (intermediaryresult != null)
{
foreach (DisBirim institution in intermediaryresult)
{
result.Add(institution);
}
}
}
catch (Exception Hata)
{
this.yazHata(Hata);
}
return result;
}
public void Dispose()
{
this._context.Dispose();
}
}
I am not sure that is a optimal approach. Do you have any recommandations? Thanks in advance.
I would recommend to read the msdn documentation
Instead of this
public TTPRepository()
{
this._errorHandling = new ErrorHandling();
this._context = new TTPDbContext();
}
try this
public TTPRepository(TTPDbContext context,ErrorHandling errorHandler)
{
this._errorHandling = errorHandler;
this._context = context;
}
By this your repository is ready to work with a context and Error Handler. I always recommend to use something like IErrorHandler and IDbContext rather than concrete classes.
So you have freedom to initialize like this. Even if you use IoC containers you can control the lifetime of your Context.
var yourRepo = new TTPRepository(new TTPDbContext());
When use repository pattern and interface best practice is that use IoC Container for inject DbContext to repository constructor.
If you are using an IoC Container, you can control the lifetime of the DbContext to ensure that all instances of Repository get the same Context.
you must one of IoC containers likes Unity, Ninject, Autofac, ...
Documentation of unity usage Dependency Injection in ASP.NET MVC - An Introduction
I use unit of work pattern with entityFramework code first. Now I want to use Autofac to register UnitOfWork, Repositories and My dbContext.
This Is my UnitOfWork code:
public class UnitOfWork : IUnitOfWork
{
private readonly DbContext _context;
public UnitOfWork(DbContext context)
{
_context = context;
Contact = new ContractRepository(context);
}
public void Dispose()
{
_context.Dispose();
GC.SuppressFinalize(_context);
}
public IContactRepository Contact { get; private set; }
public int Complete()
{
return _context.SaveChanges();
}
}
and this is my repository:
public class Repository<Entity> : IRepository<Entity> where Entity : class
{
protected readonly DbContext _noteBookContext;
public Repository(DbContext noteBookContext)
{
_noteBookContext = noteBookContext;
}
public void Add(Entity entity)
{
_noteBookContext.Set<Entity>().Add(entity);
}
}
and this is one of my repositories:
public class ContractRepository: Repository<Contact>,IContactRepository
{
public ContractRepository(DbContext noteBookContext) : base(noteBookContext)
{
}
public DbContext NotebookContext
{
get
{
return _noteBookContext;
}
}
}
and this is my db context class:
public class NoteBookContext:DbContext
{
public NoteBookContext(string connectionstring):base(connectionstring)
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ContactConfig());
modelBuilder.Configurations.Add(new PhoneConfig());
modelBuilder.Configurations.Add(new PhoneTypeConfig());
modelBuilder.Configurations.Add(new GroupConfig());
base.OnModelCreating(modelBuilder);
}
public DbSet<Contact> Contacts { get; set; }
public DbSet<Phone> Phones { get; set; }
public DbSet<Group> Groups { get; set; }
public DbSet<PhoneType> PhoneTypes { get; set; }
}
Now I want to register UnitOfWork with constructor (a constructor like this: )
var uow = new UnitOfWork(new NotebookdbContext("connectionstring"));
Note that NoteBookContext is my entity framework model.
I write registration but I got Error:
var builder = new ContainerBuilder();
builder.RegisterType<NoteBookContext>()
.As<DbContext>();
builder.RegisterType<UnitOfWork>()
.UsingConstructor(typeof(DbContext))
.As<IUnitOfWork>();
builder.RegisterGeneric(typeof(Repository<>))
.As(typeof(IRepository<>))
.InstancePerLifetimeScope();
Container container = builder.Build();
This is my error:
An unhandled exception of type 'Autofac.Core.DependencyResolutionException' occurred in Autofac.dll
Additional information: None of the constructors found with 'Autofac.Core.Activators.Reflection.DefaultConstructorFinder' on type 'DataLayer.NoteBookContext' can be invoked with the available services and parameters:
Cannot resolve parameter 'System.String connectionstring' of
constructor 'Void .ctor(System.String)'.
Edit 2 :
after help from Cyril Durand's answer I write following registering config:
var builder = new ContainerBuilder();
builder.RegisterType<ConnectionStringProvider>().As<IConnectionStringProvider>();
builder.RegisterType<NoteBookContext>().As<DbContext>().WithParameter((pi, c) => pi.Name == "connectionstring",
(pi, c) => c.Resolve<IConnectionStringProvider>().ConnectionString);
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().WithParameter(ResolvedParameter.ForNamed<DbContext>("connectionstring"));
builder.RegisterGeneric(typeof(Repository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();
and In my code :
using (var scope = DependencyInjection.Container.BeginLifetimeScope())
{
var ConnectionString = scope.Resolve<IConnectionStringProvider>();
ConnectionString.ConnectionString = "Context";
var uw = scope.Resolve<IUnitOfWork>();
var a =uw.Contact.GetAll();
}
but I got Error again:
An unhandled exception of type 'Autofac.Core.DependencyResolutionException' occurred in Autofac.dll
Additional information: An exception was thrown while invoking the
constructor 'Void .ctor(System.String)' on type 'NoteBookContext'.
can everyone help me?
The error message :
An unhandled exception of type Autofac.Core.DependencyResolutionException occurred in Autofac.dll
Additional information: None of the constructors found with Autofac.Core.Activators.Reflection.DefaultConstructorFinder on type DataLayer.NoteBookContext can be invoked with the available services and parameters:
Cannot resolve parameter System.String connectionstring of constructor Void .ctor(System.String).
tells you that Autofac can't create a NoteBookContext because it can't resolve a parameter named connectionstring of type String.
Your NoteBookContext implementation needs a connectionstring, Autofac can't know it without you telling it. When you register the NoteBookContext you will have to specify the connectionstring :
builder.RegisterType<NoteBookContext>()
.As<DbContext>()
.WithParameter("connectionstring", "XXX");
Another solution with dynamic resolution and a IConnectionStringProvider interface :
public interface IConnectionStringProvider
{
public String ConnectionString { get; }
}
and registration :
builder.RegisterType<ConnectionStringProvider>()
.As<IConnectionStringProvider>()
.InstancePerLifetimeScope();
builder.RegisterType<NoteBookContext>()
.As<DbContext>()
.WithParameter((pi, c) => pi.Name == "connectionstring",
(pi, c) => c.Resolve<IConnectionStringProvider>().ConnectionString)
.InstancePerLifetimeScope();
It's hard to tell without seeing error. But You don't need to use UsingConstructor.
//Make DbContext per request, if your app is web app (which has http request).
builder.RegisterType<NoteBookContext>()
.As<DbContext>().WithParameter("connectionstring","ConnectionStringValue").InstancePerLifetimeScope();
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(Repository<>))
.As(typeof(IRepository<>))
.InstancePerLifetimeScope();
Container = builder.Build();
Is there a reason you want to pass the connection string to your context? Create an interface for your unitofwork and do something like this:
public class NoteBookContext:DbContext
{
//Change connectionstring below with the name of your connection string in web.config
public NoteBookContext():base("name=connectionstring")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ContactConfig());
modelBuilder.Configurations.Add(new PhoneConfig());
modelBuilder.Configurations.Add(new PhoneTypeConfig());
modelBuilder.Configurations.Add(new GroupConfig());
base.OnModelCreating(modelBuilder);
}
public DbSet<Contact> Contacts { get; set; }
public DbSet<Phone> Phones { get; set; }
public DbSet<Group> Groups { get; set; }
public DbSet<PhoneType> PhoneTypes { get; set; }
}
And register like this:
var builder = new ContainerBuilder();
builder.RegisterType<NoteBookContext>()
.As<DbContext>()
.InstancePerLifetimeScope();
builder.RegisterType<UnitOfWork>()
.As<IUnitOfWork>()
.InstancePerLifetimeScope();
builder.RegisterGeneric(typeof(Repository<>))
.As(typeof(IRepository<>))
.InstancePerLifetimeScope();
Container container = builder.Build();
Getting the following error:
Schema specified is not valid. Errors:
The types in the assembly 'x, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null' cannot be loaded because the assembly contains
the EdmSchemaAttribute, and the closure of types is being loaded by
name. Loading by both name and attribute is not allowed.
What does this error mean exactly?
I'm trying to shoe-horn into my application an EF model from an existing database.
Before this application was based on CodeFirst and using the repository pattern but for the life of me I can't get this working.
Before I had:
public class BaseModelContext : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Role> Roles { get; set; }
}
But in a EF model-first scenario (one where tables already exist in the db), I had to remove these as it didn't seem to like having a repository pattern on DbSet properties.
So I stripped these out, and the repository can then use repository on the classes already defined on the .designer.cs context class (the EF model). This has the EdmSchemaAttribute set inside the generated code.
So how do I get my repository pattern to work in the model-first scenario? What does the above error mean exactly?
EDIT
Added new code:
public class BaseModelContext : DbContext
{
// public DbSet<Location> Locations { get; set; }
public BaseModelContext(string nameOrConnection)
: base(nameOrConnection)
{
}
public BaseModelContext()
{
}
}
public class VisitoriDataContext : BaseModelContext
{
public VisitoriDataContext()
: base("visitoriDataConnection")
{
}
}
public interface IVisitoriDataContextProvider
{
VisitoriDataContext DataContext { get; }
}
public class VisitoriDataContextProvider : IVisitoriDataContextProvider
{
public VisitoriDataContext DataContext { get; private set; }
public VisitoriDataContextProvider()
{
DataContext = new VisitoriDataContext();
}
}
public class VisitoriRepository<T> : IRepository<T> where T : class
{
protected readonly IVisitoriDataContextProvider _ctx;
public VisitoriRepository(IVisitoriDataContextProvider ctx)
{
_ctx = ctx;
}
public T Get(int id)
{
return _ctx.DataContext.Set<T>().Find(id);
}
}
public interface ILocationRepo : IRepository<Location>
{
IEnumerable<Location> GetSuggestedLocationsByPrefix(string searchPrefix);
}
public class LocationRepo : VisitoriRepository<Location>, ILocationRepo
{
public LocationRepo(IVisitoriDataContextProvider ctx)
: base(ctx)
{
}
public IEnumerable<Location> GetSuggestedLocationsByPrefix(string searchPrefix)
{
return Where(l => l.name.Contains(searchPrefix)).ToList();
}
}
The error means that you cannot combine code first mapping (data annotations and fluent API) and EDMX mapping (with EntityObjects!) for entity with the same name. These two approaches are disjunctive.
The rest of your question is not clear.
Btw. building mapping from existing database is called database first not model first.
Decorate the assembly containing the GILayerModel type with [assembly: EdmSchema] attribute.
In my case, I had a class that derived from an entity (code-first class) in another assembly, and I was adding an instance of this class to the DBContext:
in DBEntities project:
public class GISLayer
{
[Key]
[DatabaseGenerated(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity)]
public int GISLayerId { get; set; }
[StringLength(200)]
public string LayerName { get; set; }
public List<GISNode> Nodes { get; set; }
}
in the second assembly:
public class GISLayerModel : DBEntities.GISLayer
{
public new List<GISNodeModel> NodesModel { get; set; }
}
and the cause of error:
[WebMethod]
public void SaveGISLayers(GISLayerModel[] layers)
{
using (DBEntities.DBEntities db = new DBEntities.DBEntities())
{
foreach (var l in layers)
{
if (l.GISLayerId > 0)
{
db.GISLayers.Attach(l); //attaching a derived class
db.Entry(l).State = System.Data.EntityState.Modified;
}
else
db.GISLayers.Add(l); //adding a derived class
SaveGISNodes(l.NodesModel.ToArray(), db);
}
db.SaveChanges();
}
}
So, I used AutoMapper to copy properties of derived class to a new instance of base class:
DBEntities.GISLayer gl = AutoMapper.Mapper.Map<DBEntities.GISLayer>(l);
if (gl.GISLayerId > 0)
{
db.GISLayers.Attach(gl);
db.Entry(gl).State = System.Data.EntityState.Modified;
}
else
db.GISLayers.Add(gl);
That solved the problem.