问题
I have an old project developed with the Entity Framwork 4.0 which uses some complex types. Since I need to migrate it to .NET Core, I created a new project, installed all required libraries and used the command
PM> Scaffold-DbContext "Server=ServerInstance; Database=DBName; Trusted_Connection=True;"
Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models
on the existing database in order to create the new models. The problem is that it does not generate the complex type classes.
I can imagine I could replace the generated properties with by hand created complex types, use the [ComplexType]
attribute and set the property using OwnsOne
command, but I was wandering if there is a sort of auto generation option.
Is there a way to do this?
回答1:
I created a second partial class in order to add custom stuff to the created one. Added also a partial OnModelCreatingPartial method in which I define my complex types.
Here a snippet:
[Owned]
public class MyComplexType
{
public bool AField { get; set; }
public string BField { get; set; }
}
public partial class MyMainEntity
{
public MyComplexType MyComplexType { get; set; }
}
public partial class MyDbContext : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("myConnectionString",
opts => opts.CommandTimeout((int)TimeSpan.FromMinutes(10).TotalSeconds)
);
}
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder)
{
modelBuilder.Entity<MyMainEntity>().OwnsOne(e => e.MyComplexType, myComplexType =>
{
myComplexType.Property(p => p.AField).HasColumnName("ColumnNameFieldA");
myComplexType.Property(p => p.BField).HasColumnName("ColumnNameFieldB");
});
}
}
来源:https://stackoverflow.com/questions/63463226/migrate-entity-framework-4-0-to-core