Entity Framework Core 3 : Type must match overridden member - entity-framework

I have the following two dbcontexts in my Entity Framework Core solution. The OrganisationContext derives from SagitarriContext. I am overiding the base property DbSet<Person> Person. I am getting the following error in the derived class:
Error CS1715
'OrganisationContext.Person': type must be 'DbSet' to match overridden member 'SagitarriContext.Person'
DbContext
namespace Genistar.Data.DbContexts.Interfaces
{
public class SagitarriContext : DbContext, ISagitarriContext
{
public SagitarriContext();
public SagitarriContext(DbContextOptions<SagitarriContext> options);
protected SagitarriContext(DbContextOptions options);
public virtual DbSet<Person> Person { get; set; }
}
}
namespace Genistar.Data.DbContexts
{
public class OrganisationContext : SagitarriContext
{
private readonly ITimeProvider _timeProvider;
private readonly IUserContextResolverFactory _userContextResolver;
public OrganisationContext(DbContextOptions options)
: base(options)
{
}
public OrganisationContext(DbContextOptions options, ITimeProvider timeProvider, IUserContextResolverFactory userContextResolver)
: base(options)
{
_timeProvider = timeProvider;
_userContextResolver = userContextResolver;
}
public override DbSet<Person> Person { get; set; }
}
}
namespace Genistar.Data.DbContexts.Interfaces
{
public interface ISagitarriContext
{
Task<int> SaveChangesAsync(CancellationToken cancellationToken);
DbSet<TQuery> Set<TQuery>() where TQuery : class;
public DatabaseFacade Database { get; }
DbSet<Person> Person { get; set; }
}
}
Usings
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Genistar.Data.DbContexts;
using Genistar.Data.Models;
using Genistar.Organisation.Models.Representative;
using Genistar.Organisation.Models.Unregistered;
using Genistar.Organisation.Models.User;
using Person = Genistar.Organisation.Models.DataModels.Person;
using PersonNote = Genistar.Organisation.Models.DataModels.PersonNote;
using Genistar.Security.Context;
using Genistar.Security.Utility;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;

You are not in the same namespace, so the Person class used in DbSet<Person> might be a different one in Genistar.Data.DbContexts.Interfaces and Genistar.Data.DbContexts. Also, we don't see the usings, so there might be an error there.

Related

issue with new create dbcontext class object in asp.net core 2.1

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
}

Invalid Column name error in MVC 4

I have created a simple class and a list based on this class. When i try to populte this list and send to view iam getting an error. Please view my class and custom mapper model based on database.
Folloiwng is the class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MvcModal.Models
{
public class mytransaction
{
public int Id { get; set; }
public int my_trn_id { get; set; }
public string Description { get; set; }
public List<mytransaction> Translist { get; set; }
}
}
Following is the custom database mapper class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using MvcModal.Models;
namespace MvcModal.Models
{
public class PrContext : DbContext
{
static string _conString = #"Data Source=.\sqlexpress;Initial Catalog=MyDb;Integrated Security=True";
public PrContext() : base(_conString) { }
public DbSet<mytransaction> MyTransactions { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<PrContext>(null);
modelBuilder.Configurations.Add(new NewTransactMapper());
}
public class NewTransactMapper : EntityTypeConfiguration<mytransaction>
{
public NewTransactMapper()
{
this.ToTable("mytransaction");
this.Property(m => m.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
this.HasKey(m => m.my_trn_id);
}
}
}
}
Following is the error image.
Please view the red circuled error and see the mytransactions_my_trn_id text. mytransaction is my table name and my_trn_id is my column name. Rest of the columns have no issue, but this making me insane.
Please anyone guide what iam missing and how can i make my table name and column isolate and resolve this error. Thanks in advance.
If you want to create the model you have to know wich columns EF generates to handle relationships and if you don't specify the names (as in this case) you have to know wich name EF will assign to properties.
I suggest you (I do this) to generate the model on an empty database with EF standard migrations then copy the structure from the EF created database.
In your case you only need to add the column mytransaction_my_trn_id of type int (same as id). If you need the same database the EF would generate with migrations, you need also to add an index on that column and a relationship from that column to my_trn_id column (primary key).
I have done it using the following code. It may also be help someone. Also thanks to everyone for their nice suggestions.
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Configuration;
using payorder_draft_printing.Controllers;
namespace payorder_draft_printing.Models
{
public class context_db : DbContext
{
static string _conString = #"Data Source=my datasource";
public context_db()
: base(_conString)
{
Database.SetInitializer<context_db>(null);
}
public IDbSet<sms_description> sms_description { get; set; }
public IDbSet<sms_imported_trn_code> sms_imported_trn_code { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new sms_description_mapper());
modelBuilder.Configurations.Add(new sms_imported_trn_code_mapper());
}
}
class sms_description_mapper : EntityTypeConfiguration<sms_description>
{
public sms_description_mapper()
{
ToTable("dbo.sms_description");
this.Property(x => x.id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasKey(x => x.trn_code);
Property(x => x.trn_code).HasColumnName("trn_code").IsRequired();
}
}
class sms_imported_trn_code_mapper : EntityTypeConfiguration<sms_imported_trn_code>
{
public sms_imported_trn_code_mapper()
{
ToTable("dbo.sms_imported_trn_code");
HasKey(x => x.trn_code);
this.Property(x => x.id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.trn_code).HasColumnName("trn_code").IsRequired();
}
}
}

Error comes as a {"Invalid object name 'dbo.TableName'."}

I'm using Entity Framework and MVC3,
I have used Model First approch...
I have used Company as a Base class and I have inherited the Lead Class from it.
When I run the application its gives an error...
This is Base Class
using System;
using System.Collections.Generic;
namespace CRMEntities
{
public partial class Company
{
public int Id { get; set; }
}
}
This is Lead Class (Child)
using System;
using System.Collections.Generic;
namespace CRMEntities
{
public partial class Lead : Company
{
public Lead()
{
this.Status = 1;
this.IsQualified = false;
}
public Nullable<short> Status { get; set; }
public Nullable<bool> IsQualified { get; set; }
}
}
I have added the controller,and in index view I have added this code...
public class Default1Controller : Controller
{
private CRMWebContainer db = new CRMWebContainer();
//
// GET: /Default1/
public ViewResult Index()
{
return View(db.Companies.OfType<Lead>().ToList());
}
}
This is DB and Model ...
Its giving the inner error -
{"An error occurred while executing the command definition. See the
inner exception for details."} {"Invalid object name
'dbo.Companies'."}
Do you have a Companies table or Company table in your database. It looks like you have a Mapping issue. Entity Framework will make some guesses as to how it pluralizes entity names by default.

seed method not called with EntityFramework CodeFirst

I've been struggling on and off with this problem since 4.1 (now I'm on 4.3). It seems to me that to get the seed method called, all I should have to do is the following:
1) Create an empty data catalog on sqlserver
2) Execute the code below:
Database.SetInitializer(new DropCreateDatabaseAlways<SiteDB>());
I have my SiteDB defined as follows:
public class SiteDBInitializer :
DropCreateDatabaseAlways<SiteDB>
{
protected override void Seed(SiteDB db)
{
... (break point set here that never gets hit)
I feel like I must be missing something very simple because this creates my tables, but does never calls the seed method.
To Make this more clear, here is a full example that includes all the code. When I run it, seed never gets called:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Data.Entity;
namespace ConApp
{
internal class Program
{
private static void Main(string[] args)
{
Database.SetInitializer(new SiteDBInitializer());
using (var db = new SiteDB())
{
var x = db.Customers;
}
}
}
public class SiteDB : DbContext
{
public DbSet<Customer> Customers { get; set; }
}
public class Customer
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
public string LastName { get; set; }
}
public class SiteDBInitializer :
DropCreateDatabaseAlways<SiteDB>
{
protected override void Seed(SiteDB db)
{
db.Customers.Add(new Customer() {LastName = "Kellner"});
db.Customers.Add(new Customer() {LastName = "Jones"});
db.Customers.Add(new Customer() {LastName = "Smith"});
db.SaveChanges();
}
}
}
You need call Database.SetInitializer(new SiteDBInitializer()); instead.
I looked at all the answers for that, nothing really works, and I wonder if that's a Microsoft bug for not calling the Seed method when DB does not exists.
The only code that worked, was to actually make the class call the seed if DB does not exists:
Context class:
class AlisDbContext : DbContext
{
public class MyContextFactory : IDbContextFactory<AlisDbContext>
{
public AlisDbContext Create()
{
return new AlisDbContext("CompactDBContext");
}
}
public AlisDbContext(string nameOrConnectionString) : base(nameOrConnectionString)
{
Database.SetInitializer(new AlisDbInitializer(this));
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<AlisDbContext>());
}
public DbSet<SavedCredentials> SavedCredentialses { get; set; }
}
Then AlisDbInitializer need to check and call the seed method like:
public AlisDbInitializer(AlisDbContext alisDbContext)
{
if (!alisDbContext.Database.Exists())
{
Seed(alisDbContext);
}
}

Schema invalid and types cannot be loaded because the assembly contains EdmSchemaAttribute

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.