dbcontext - non dbo owner - entity-framework

I'm using EF 5 to connect to my tables, but my tables don't have dbo as the owner. EF 5 queries insert dbo as the default owner. Can you tell me how to override this? Here are some code snippets:
public class MessageBoardContext : DbContext
{
public MessageBoardContext()
: base("DefaultConnection")
{
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
Database.SetInitializer(
new MigrateDatabaseToLatestVersion<MessageBoardContext, MessageBoardMigrationsConfiguration>()
);
}
public DbSet<Topic> Topics { get; set; }
public DbSet<Reply> Replies { get; set; }
}
public class MessageBoardRepository : IMessageBoardRepository
{
MessageBoardContext _ctx;
public MessageBoardRepository(MessageBoardContext ctx)
{
_ctx = ctx;
}
public IQueryable<Topic> GetTopics()
{
return _ctx.Topics; //Uses dbo.Topics here! Which I don't want.
}
}

Found it! Here is the link:
http://devproconnections.com/entity-framework/working-schema-names-entity-framework-code-first-design
Here is a quick code snippet:
public class OrderingContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().ToTable("Customers", schemaName: "Ordering");
}}

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

EF6 with SQLite - not restoring lists

I am using EF6 to read and write rules for some validation to an SQLite DB. Code First approach. I successfully wrote the rules out to DB. As I tried to read them now, the complex rules which contain child rules seem to have empty lists of child rules, despite database mirroring that correctly. What is wrong there?
The class hierarchy is:
abstract Rule - abstract class with "Validate" method.
abstract ComplexRule: Rule - a rule which can have child rules
SuperRule, OrRule, AndRule : ComplexRule implementations
BasicRule: Rule - direct implmentation which does some pattern matching.
The Table as written out in DB is so:
RuleId,Condition,Value,Mode,Discriminator,ComplexRule_RuleId
1,,,,SuperRule,
2,*USA*,*PATT1*,1,BasicRule,1
3,*CHN*,*PATT2*,1,BasicRule,1
Reading code looks like this:
using (var db = new RuleModel())
{
var q = db.Rules.OfType<SuperRule>).FirstOrDefault();
}
it results in a SuperRule which Children are empty. The db.Rules contains all 3 rules, but there's no association between BasicRule and SuperRule.
The RuleModel (DbContext) looks like this:
public class RuleModel : DbContext
{
public RuleModel() : base("name=RuleModel")
{
}
public virtual DbSet<Rule> Rules { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var sqliteConnectionInitializer = new SqliteCreateDatabaseIfNotExists<RuleModel>(modelBuilder);
Database.SetInitializer(sqliteConnectionInitializer);
}
}
The Rules look like this:
public abstract class Rule
{
[Key]
public int RuleId { get; set; }
public abstract RuleResult Match(Mapping m);
}
public abstract class ComplexRule: Rule
{
public IList<Rule> ChildRules { set; get; }
public ComplexRule()
{
ChildRules = new List<Rule>();
}
}
public class OrRule : ComplexRule
{
public override RuleResult Match(Mapping m)
{
// Some logics
}
public OrRule() : base() { }
}
public class SuperRule: OrRule
{
public override RuleResult Match(Mapping m)
{
//some logics
}
public SuperRule() : base()
{
}
}
public class BasicRule : Rule
{
public string Condition { set; get; }
public string Value { set; get; }
public RuleMode Mode { set; get; }
public BasicRule(string condition, string value, RuleMode mode = RuleMode.MODE_ANYWHERE)
{
Condition = condition;
Value = value;
Mode = mode;
}
public BasicRule() { }
public override RuleResult Match(Mapping m)
{
// logics
}
}

Entity Framework CodeFirst, Add Dbset to DbContext, programmatically

how can i Add DbSet to my dbContext class, programmatically.
[
public class MyDBContext : DbContext
{
public MyDBContext() : base("MyCon")
{
Database.SetInitializer<MyDBContext>(new CreateDatabaseIfNotExists<MyDBContext>());
}
//Do this part programatically:
public DbSet<Admin> Admins { get; set; }
public DbSet<MyXosh> MyProperty { get; set; }
}
][1]
i want to add my model classes by ((C# Code-DOM)) and of course i did. but now i have problem with creating DbSet properties inside my Context class ...
yes i did!..
this: https://romiller.com/2012/03/26/dynamically-building-a-model-with-code-first/
And this: Create Table, Run Time using entity framework Code-First
are solution. no need to dispute with dbSets directly. it just works by do some thing like that:
public class MyDBContext : DbContext
{
public MyDBContext() : base("MyCon")
{
Database.SetInitializer<MyDBContext>(new CreateDatabaseIfNotExists<MyDBContext>());
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
var entityMethod = typeof(DbModelBuilder).GetMethod("Entity");
var theList = Assembly.GetExecutingAssembly().GetTypes()
.Where(t => t.Namespace == "FullDynamicWepApp.Data.Domins")
.ToList();
foreach (var item in theList)
{
entityMethod.MakeGenericMethod(item)
.Invoke(modelBuilder, new object[] { });
}
base.OnModelCreating(modelBuilder);
}
}
For those using EF Core that stubble here:
The code below is only for one table with the generic type. If you want more types you can always pass them through the constructor and run a cycle.
public class TableContextGeneric<T> : DbContext where T : class
{
private readonly string _connectionString;
//public virtual DbSet<T> table { get; set; }
public TableContextGeneric(string connectionString)
{
_connectionString = connectionString;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var entityMethod = typeof(ModelBuilder).GetMethods().First(e => e.Name == "Entity");
//the cycle will be run here
entityMethod?.MakeGenericMethod(typeof(T))
.Invoke(modelBuilder, new object[] { });
base.OnModelCreating(modelBuilder);
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(_connectionString); // can be anyone
}
}

Seeding not working in Entity Framework Code First Approach

I am developing a .Net project. I am using entity framework code first approach to interact with database. I am seeding some mock data to my database during development. But seeding is not working. I followed this link - http://www.entityframeworktutorial.net/code-first/seed-database-in-code-first.aspx.
This is my ContextInitializer class
public class ContextInitializer : System.Data.Entity.CreateDatabaseIfNotExists<StoreContext>
{
protected override void Seed(StoreContext context)
{
IList<Brand> brands = new List<Brand>();
brands.Add(new Brand { Name = "Giordano" ,TotalSale = 1 });
brands.Add(new Brand { Name = "Nike" , TotalSale = 3 });
foreach(Brand brand in brands)
{
context.Brands.Add(brand);
}
base.Seed(context);
context.SaveChanges();
}
}
This is my context class
public class StoreContext : DbContext,IDisposable
{
public StoreContext():base("DefaultConnection")
{
Database.SetInitializer(new ContextInitializer());
}
public virtual DbSet<Category> Categories { get; set; }
public virtual DbSet<Brand> Brands { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
This is my brand class
public class Brand
{
public int Id { get; set; }
[Required]
[MaxLength(40)]
public string Name { get; set; }
public int TotalSale { get; set; }
}
I searched solutions online and I followed instructions. I run context.SaveChanges as well. But it is not seeding data to database. Why it is not working?
You are taking the wrong initializer, CreateDatabaseIfNotExists is called only if the database not exists!
You can use for example DropCreateDatabaseIfModelChanges:
Solution 1)
public class ContextInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<StoreContext>
{
You have to take care with this approach, it !!!removes!!! all existing data.
Solution 2)
Create a custom DbMigrationsConfiguration:
public class Configuration : DbMigrationsConfiguration<StoreContext>
{
public Configuration()
{
// Take here! read about this property!
this.AutomaticMigrationDataLossAllowed = true;
this.AutomaticMigrationsEnabled = false;
}
protected override void Seed(StoreContext context)
{
IList<Brand> brands = new List<Brand>();
brands.Add(new Brand { Name = "Giordano", TotalSale = 1 });
brands.Add(new Brand { Name = "Nike", TotalSale = 3 });
foreach (Brand brand in brands)
{
context.Brands.AddOrUpdate(m => m.Name, brand);
}
base.Seed(context);
context.SaveChanges();
}
}
In this way you can called( !!Before you create the DbContext or in the DbContext constructor!!):
// You can put me also in DbContext constuctor
Database.SetInitializer(new MigrateDatabaseToLatestVersion<StoreContext , Yournamespace.Migrations.Configuration>("DefaultConnection"));
Notes:
DbMigrationsConfiguration need to know about the connection string you can provide this info in the constructor or from outside.
In Your DbMigrationsConfiguration you can configure also:
MigrationsNamespace
MigrationsAssembly
MigrationsDirectory
TargetDatabase
If you leave everything default as in my example then you do not have to change anything!
Setting the Initializer for a Database has to happen BEFORE the context is ever created so...
public StoreContext():base("DefaultConnection")
{
Database.SetInitializer(new ContextInitializer());
}
is much to late. If you made it static, then it could work:
static StoreContext()
{
Database.SetInitializer(new ContextInitializer());
}
Your code is working if you delete your existing database and the EF will create and seeding the data
Or
You can use DbMigrationsConfiguration insted of CreateDatabaseIfNotExists and change your code as follow:
First you have to delete the existing database
ContextInitializer class
public class ContextInitializer : System.Data.Entity.Migrations.DbMigrationsConfiguration<StoreContext>
{
public ContextInitializer()
{
this.AutomaticMigrationDataLossAllowed = true;
this.AutomaticMigrationsEnabled = true;
}
protected override void Seed(StoreContext context)
{
IList<Brand> brands = new List<Brand>();
brands.Add(new Brand { Name = "Giordano", TotalSale = 1 });
brands.Add(new Brand { Name = "Nike", TotalSale = 3 });
foreach (Brand brand in brands)
{
context.Brands.AddOrUpdate(m => m.Name, brand);
}
base.Seed(context);
context.SaveChanges();
}
}
StoreContext
public class StoreContext : DbContext, IDisposable
{
public StoreContext() : base("DefaultConnection")
{
Database.SetInitializer(new MigrateDatabaseToLatestVersion<StoreContext, ContextInitializer>());
// Database.SetInitializer(new ContextInitializer());
}
public virtual DbSet<Category> Categories { get; set; }
public virtual DbSet<Brand> Brands { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
}
}
Then any change in your seed will automatically reflected to your database

Who moved my Database property?

I have the following DbContext code working in a project with EF 6.1.0, yet with 6.1.1 I get complaints that Database is not static. Any suggestions:
public class DataMonitorDbContext : DbContext
{
private static readonly ImportConfig Config = ImportConfig.Read();
static DataMonitorDbContext() {
Database.SetInitializer<DataMonitorDbContext>(null);
}
public DataMonitorDbContext(string connString = null)
: base(!string.IsNullOrEmpty(connString) ? connString : ConnectionString) {
}
public DbSet<DataRecord> DataRecords { get; set; }
public DbSet<LogEntry> LogEntries { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
modelBuilder.Configurations.Add(new DataRecordMap());
modelBuilder.Configurations.Add(new LogEntryMap());
}
private static string ConnectionString {
get {
return "Data Source=" + Config.DatabasePath;
}
}
}
Have you tried using the complete namespace?
System.Data.Entity.Database.SetInitializer<DataMonitorDbContext>(null);
If that works, then you have not included the correct namespaces, or you have a namespace conflict.