seed method not called with EntityFramework CodeFirst - entity-framework

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

Related

Separate copy of DbContext class for unit testing?

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

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
}

Entity Framework Core 3 : Type must match overridden member

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.

System.Data.SqlClient.SqlException: Invalid object name 'dbo.__TransactionHistory'

I get the error
"System.Data.SqlClient.SqlException: Invalid object name
'dbo.__TransactionHistory'."
when I try creating a new dbcontext using the TransactionContext in EF 6.1.3. It seems like a bug where it's using the transactioncontext API before the DBMigrator/Initializer even has a chance to create it since these operations are done within a transaction.
Below is the code that replicates the problem
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.SqlServer;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
new SomeDbContext().Database.Initialize(false);
}
public class Person
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
public class MyConfiguration : DbConfiguration
{
public MyConfiguration()
{
SetTransactionHandler(SqlProviderServices.ProviderInvariantName, () => new CommitFailureHandler());
}
}
[DbConfigurationType(typeof(MyConfiguration))]
public class SomeDbContext : DbContext
{
static SomeDbContext()
{
Database.SetInitializer(new DropCreateDatabaseAlways());
}
public SomeDbContext()
: base(#"Data Source=.;Initial Catalog=SomeDbContext;Integrated Security=True;MultipleActiveResultSets=True;Connect Timeout=1;")
{
}
public virtual DbSet People { get; set; }
}
}
}
I ended up doing two things.
Manually run the SQL CREATE TABLE [dbo].[__TransactionHistory] (
[Id] [uniqueidentifier] NOT NULL,
[CreationTime] [datetime] NOT NULL,
CONSTRAINT [PK_dbo.__TransactionHistory] PRIMARY KEY ([Id])
Creating a CommitFailureHandler that overrides the BeganTransaction to not call the base method until the table has been created

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.