I'm having trouble understanding the rules around when SeedData is called in EF Code First. Specifically, does it have anything to do with migrations? Migrations has it's own place to seed that seems different from the datacontext. I'm showing two examples below and I'm not sure which one is correct to use.
My Main Question: If I have a Migration, does the seeddata method not get called in my MultiTenantContext class? I have examples where it does and it does not and I can't figure out why.
In Migrations configuration.cs:
namespace WebApp.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<WebApp.Models.MultiTenantContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
ContextKey = "WebApp.Models.MultiTenantContext";
}
protected override void Seed(WebApp.Models.MultiTenantContext context)
{
var tenants = new List<Tenant>
{...};
tenants.ForEach(a => context.Tenants.Add(a));
context.SaveChanges();
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
}
And in context class directly:
[DbConfigurationType(typeof(DataConfiguration))]
public class MultiTenantContext : DbContext
{
public DbSet<Tenant> Tenants { get; set; }
}
public class DataConfiguration : DbConfiguration
{
public DataConfiguration()
{
SetDatabaseInitializer(new MultiTenantContextInitializer());
}
}
public class MultiTenantContextInitializer :
CreateDatabaseIfNotExists<MultiTenantContext>
{
protected override void Seed(MultiTenantContext context)
{
var tenants = new List<Tenant>
{...}
tenants.ForEach(a => context.Tenants.Add(a));
context.SaveChanges();
}
}
Related
we are using ef core 3.1
And we want to use dynamic query filter,
I tried sample implementation but did not work correctly we expected, filtering always same tenant id,i tried to explain at below
public class TestDbContext : DbContext
{
public DbSet<TenantUser> TenantUsers { get; set; }
private readonly ITenantProvider _tenantProvider;
private Guid? TenantId => _tenantProvider.TenantId;
public TestDbContext (DbContextOptions<TestDbContext > options, ITenantProvider tenantProvider) : base(options)
{
_tenantProvider = tenantProvider;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<TenantUser>()
.HasQueryFilter(p => EF.Property<Guid>(p, "TenantId") == TenantId);
}
}
ITenantProvider returns TenantId from HttpContext headers
this code filtering always same tenant id from coming first request
Update:
public class TenantProvider : ITenantProvider
{
private readonly IHttpContextAccessor _httpContextAccessor;
public TenantProvider(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}
public Guid? TenantId
{
get
{
if (_httpContextAccessor.HttpContext.Request.Headers.TryGetValue(HeaderNames.TenantId, out var tenantId) &&
Guid.TryParse(tenantId, out Guid parsedTenantId))
{
return parsedTenantId;
}
return null;
}
}
}
For example
First Request TenantId = 60000000-0000-0000-0000-000000000000
This filter => 60000000-0000-0000-0000-000000000000
Second Request TenantId = 10000000-0000-0000-0000-000000000000
This filter => 60000000-0000-0000-0000-000000000000
We tried something similar like that a few years ago. Main problem is here that OnModelCreating method only triggered once. So HasQueryFilter works once and gets the current tenant id from provider and it applies to all queries the same tenant id.
You should also implement a custom IModelCacheKeyFactory
public class MyModelCacheKeyFactory : IModelCacheKeyFactory
{
public object Create(DbContext context)
{
if (context is TestDbContext testDbContext)
{
return (context.GetType(), testDbContext.TenantId);
}
return context.GetType();
}
}
And then, you need to replace like this
var builder = new DbContextOptionsBuilder<TestDbContext>();
builder.ReplaceService<IModelCacheKeyFactory, MyModelCacheKeyFactory>();
var context = new TestDbContext(builder.Options);
Reference:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.entityframeworkcore.infrastructure.imodelcachekeyfactory
I am using EF Core 3.1.7. The DbContext has the UseLazyLoadingProxies set. Fluent API mappings are being used to map entities to the database. I have an entity with a navigation property that uses a backing field. Loads and saves to the database seem to work fine except for an issue when accessing the backing field before I access the navigation property.
It seems that referenced entities don't lazy load when accessing the backing field. Is this a deficiency of the Castle.Proxy class or an incorrect configuration?
Compare the Student class implementation of IsRegisteredForACourse to the IsRegisteredForACourse2 for the behavior in question.
Database tables and relationships.
Student Entity
using System.Collections.Generic;
namespace EFCoreMappingTests
{
public class Student
{
public int Id { get; }
public string Name { get; }
private readonly List<Course> _courses;
public virtual IReadOnlyList<Course> Courses => _courses.AsReadOnly();
protected Student()
{
_courses = new List<Course>();
}
public Student(string name) : this()
{
Name = name;
}
public bool IsRegisteredForACourse()
{
return _courses.Count > 0;
}
public bool IsRegisteredForACourse2()
{
//Note the use of the property compare to the previous method using the backing field.
return Courses.Count > 0;
}
public void AddCourse(Course course)
{
_courses.Add(course);
}
}
}
Course Entity
namespace EFCoreMappingTests
{
public class Course
{
public int Id { get; }
public string Name { get; }
public virtual Student Student { get; }
protected Course()
{
}
public Course(string name) : this()
{
Name = name;
}
}
}
DbContext
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
namespace EFCoreMappingTests
{
public sealed class Context : DbContext
{
private readonly string _connectionString;
private readonly bool _useConsoleLogger;
public DbSet<Student> Students { get; set; }
public DbSet<Course> Courses { get; set; }
public Context(string connectionString, bool useConsoleLogger)
{
_connectionString = connectionString;
_useConsoleLogger = useConsoleLogger;
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
{
builder
.AddFilter((category, level) =>
category == DbLoggerCategory.Database.Command.Name && level == LogLevel.Information)
.AddConsole();
});
optionsBuilder
.UseSqlServer(_connectionString)
.UseLazyLoadingProxies();
if (_useConsoleLogger)
{
optionsBuilder
.UseLoggerFactory(loggerFactory)
.EnableSensitiveDataLogging();
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Student>(x =>
{
x.ToTable("Student").HasKey(k => k.Id);
x.Property(p => p.Id).HasColumnName("Id");
x.Property(p => p.Name).HasColumnName("Name");
x.HasMany(p => p.Courses)
.WithOne(p => p.Student)
.OnDelete(DeleteBehavior.Cascade)
.Metadata.PrincipalToDependent.SetPropertyAccessMode(PropertyAccessMode.Field);
});
modelBuilder.Entity<Course>(x =>
{
x.ToTable("Course").HasKey(k => k.Id);
x.Property(p => p.Id).HasColumnName("Id");
x.Property(p => p.Name).HasColumnName("Name");
x.HasOne(p => p.Student).WithMany(p => p.Courses);
});
}
}
}
Test program which demos the issue.
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
using System.Linq;
namespace EFCoreMappingTests
{
class Program
{
static void Main(string[] args)
{
string connectionString = GetConnectionString();
using var context = new Context(connectionString, true);
var student2 = context.Students.FirstOrDefault(q => q.Id == 5);
Console.WriteLine(student2.IsRegisteredForACourse());
Console.WriteLine(student2.IsRegisteredForACourse2()); // The method uses the property which forces the lazy loading of the entities
Console.WriteLine(student2.IsRegisteredForACourse());
}
private static string GetConnectionString()
{
IConfigurationRoot configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
return configuration["ConnectionString"];
}
}
}
Console Output
False
True
True
When you declare a mapped property in an EF entity as virtual, EF generates a proxy which is capable of intercepting requests and assessing whether the data needs to be loaded. If you attempt to use a backing field before that virtual property is accessed, EF has no "signal" to lazy load the property.
As a general rule with entities you should always use the properties and avoid using/accessing backing fields. Auto-initialization can help:
public virtual IReadOnlyList<Course> Courses => new List<Course>().AsReadOnly();
I am using entity framework for my DAL and want to convert entities objects to business objects and vice versa. This is taking place in my BLL project. I am hoping to setup automapper in my BLL project to take... let say Customer.cs auto generated by EF and convert it to CustomerWithDifferentDetail.cs (my business obj)
I attempted to create an AutoMapperBLLConfig.cs under BLL project with the following code:
public static void Configure()
{
Mapper.Initialize(cfg =>
{
cfg.AddProfile(new CustomerProfile());
});
}
public class CustomerProfile : Profile
{
protected override void Configure()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Customer, CustomerWithDifferentDetail>();
cfg.CreateMap<CustomerWithDifferentDetail, Customer>();
});
}
}
Then I created CustermerService.cs under BLL project with the following code to test if it's working:
public void CustomerToCustomerWithDifferentDetail()
{
AutoMapperBLLConfiguration.Configure();
Customer source = new Customer
{
Account = 1234,
Purchase_Quantity = 100,
Date = "05/05/2016",
Total = 500
};
Models.CustomerWithDifferentDetail testCustomerDTO = Mapper.Map<Customer, Models.CustomerWithDifferentDetail>(source)
}
I get this Error:
Missing type map configuration or unsupported mapping.
I am not sure what I did wrong. I don't have a start_up or global.aspx. This is a class library. I'm not sure what I'm missing or did wrong.
I have a separate project calls Models which hold all the business objects including CustomerWithDifferentDetail.cs. In this case, CustomerWithDifferentDetail only has two properties: Account and Total. If mapped, it should give me Account = 1234 and Total = 500 - basically the same data as entity object just in different shape.
======================= UPDATE=================================
AutoMapperBLLConfig.cs - stay the same as noted above
CustomerProfile.cs
public class CustomerProfile : Profile
{
protected override void Configure()
{
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Customer, CustomerWithDifferentDetail>().ReverseMap(); //cut it down to one line with ReverseMap
});
}
CreateMap<Customer, CustomerWithDifferentDetail>().ReverseMap(); //missed this one line before; hence, the error
}
CustomerService.cs
static CustomerService()
{
AutoMapperBLLConfiguration.Configure(); //per #Erik Philips suggestion, move this call to a static constructor
}
public void CustomerToCustomerWithDifferentDetail()
{
Customer source = new Customer
{
Account = 1234,
Purchase_Quantity = 100,
Date = "05/05/2016",
Total = 500
};
Models.CustomerWithDifferentDetail testCustomerDTO = Mapper.Map<Customer, Models.CustomerWithDifferentDetail>(source);
}
Result: my testCustomerDTO returns exactly what I expected.
Since you are using the instance method of AutoMapper:
var config = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Customer, CustomerWithDifferentDetail>();
cfg.CreateMap<CustomerWithDifferentDetail, Customer>();
});
Then you need to use the instance for mapping:
Models.CustomerWithDifferentDetail testCustomerDTO =
config.Map<Customer, Models.CustomerWithDifferentDetail>(source)
I personally haven't really thought this through in my applications (I need to move to the instance method instead of the static method). (Migrating from status API).
Off the cuff, based on your code, I'd probably do something like:
public class PersonDataObject
{
public string Name { get; set; }
}
public class PersonBusinessObject
{
private readonly MapperConfiguration _mapper;
public string Name { get; set; }
PersonBusinessObject()
{
_mapper = new MapperConfiguration(cfg =>
{
cfg.CreateMap<PersonDataObject,PersonBusinessObject>();
});
}
public static PersonBusinessObject MapFrom(PersonDataObject data)
{
return _mapper.Map<PersonBusinessObject>(data);
}
}
Then you can simply:
PersonDataObject data = new PersonDataObject();
PersonBusinessObject business = PersonBusinessObject.MapFrom(data);
I have a DbContext that is empty. Mappings are created dynamically and the DbContext is used generically using Set();
The following is my generic DbContext.
/// <summary>
/// Object context
/// </summary>
public class MethodObjectContext : DbContext, IDbContext
{
private readonly IEventPublisher _eventPublisher;
public MethodObjectContext(string nameOrConnectionString, IEventPublisher eventPublisher)
: base(nameOrConnectionString)
{
_eventPublisher = eventPublisher;
}
public MethodObjectContext(DbConnection existingConnection, bool contextOwnsConnection, IEventPublisher eventPublisher)
: base(existingConnection, contextOwnsConnection)
{
_eventPublisher = eventPublisher;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
_eventPublisher.Publish(new ModelCreating(modelBuilder));
base.OnModelCreating(modelBuilder);
}
public new IDbSet<TEntity> Set<TEntity>() where TEntity : class
{
return base.Set<TEntity>();
}
}
I am trying write a unit test that will assert that the database is out of sync if I change the mappings (from the ModelCreating event).
The following is my test code.
[TestClass]
public class MigrationTests
{
private string _connectionString = string.Empty;
private string _testDb = string.Empty;
public MigrationTests()
{
_testDb = Path.Combine("C:\\", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.Replace(".", "") + ".sdf");
if (File.Exists(_testDb))
File.Delete(_testDb);
_connectionString = string.Format("Data Source={0};Persist Security Info=False;", _testDb);
Database.DefaultConnectionFactory = new SqlCeConnectionFactory("System.Data.SqlServerCe.4.0");
}
[TestMethod]
public void ThrowsErrorForOutOfDateDatabase()
{
// The initializer will handle migrating the database.
// If ctor param is false, auto migration is off and an error will be throw saying the database is out of date.
Database.SetInitializer(new MigrationDatabaseInitializer<MethodObjectContext>(false));
// Create the initial database and do a query.
// This will create the database with the conventions of the Product1 type.
TryQueryType<Product1>("Product");
// The next query will create a new model that has conventions for the product2 type.
// It has an additional property which makes the database (created from previous query) out of date.
// An error should be thrown indicating that the database is out of sync.
ExceptionAssert.Throws<InvalidOperationException>(() => TryQueryType<Product2>("Product"));
}
private void TryQueryType<T>(string tableName) where T : class
{
using (var context = new MethodObjectContext(_connectionString, new FakeEventPublisher(x => x.ModelBuilder.Entity<T>().ToTable(tableName))))
{
var respository = new EfRepository<T>(context);
var items = respository.Table.ToList();
}
}
}
My Product1 class is a POCO object, and my Product2 class is the same object with an additional db field.
My problem is that when I new() up the MethodObjectContext the second time and do a query, the ModelCreating method isn't called, causing me to get the following error.
The entity type Product2 is not part of the model for the current context.
Product2 would be a part of the context of the ModelCreating event was being called, but it is not. Any ideas?
NOTE: I am expecting errors since we are using the same connection string (sdf) and the db being created didn't create the additional field that my second call (Product2) requires.
My DbCompiledModel was being cached. The following flushed the cache.
private void ClearDbCompiledModelCache()
{
var type = Type.GetType("System.Data.Entity.Internal.LazyInternalContext, EntityFramework");
var cmField = type.GetField("CachedModels",System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic);
var cachedModels = cmField.GetValue(null);
cachedModels.GetType().InvokeMember("Clear", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.InvokeMethod, null, cachedModels, null);
}
I'm using EF 3.5 and I've created partial classes with the same name as my tables and EF generated classes.
public partial class Region
{
public Region()
{
}
public Region(string name)
{
this.RegionName = name;
}
public bool Save()
{
try
{
using (var context = new PhonebookEntities())
{
context.AddToRegions(this);
context.SaveChanges();
}
return true;
}
catch (System.Exception)
{
return false;
}
}
}
When I'm create and save a new Region
var region = new Region("TestRegion");
region.Save().ShouldBeTrue();
I get an exception when I save because the region entity is autopopulated with RegionId = 0, which is setup in the db to autoincrement.