问题
I have the Client class defined. I also have Mapping\ClientMap.cs file that defines column names using Fluent API. However, I am not sure how to "invoke" it as I don't see the ClientMap.cs code being executed.
I also have this:
namespace CardNumbers.Data
{
public class Repository : DbContext, IRepository
{
public DbSet<Client> Clients { get; set; }
public DbSet<ClientOrder> ClientOrders { get; set; }
public DbSet<Reorder> Reorders { get; set; }
public DbSet<Operator> Operators { get; set; }
which I know is not a very good practice, but that's how we were building the application with the instructor.
So, my question is - what do I need to add to make sure the Fluent API code is invoked in run-time?
Thanks in advance.
回答1:
The fluent mapping should be added at the bottom of your "Repository
" class like this
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
//add fluent api code
}
The reason I am quoting your Repository is that you are not really implementing a repository pattern there. You should really have this defined as a specific DbContext, and then have a repository which can take multiple contexts. See this very well written post about implementing a repository: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
回答2:
You should place your mapping code either directly in your OnModelCreating method (which is a virtual method you can override on DbContext
), or place it in a sepearte configuration class which is then invoked from the OnModelCreating
method.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Client>().Property(p => p.Name).IsRequired();
}
or
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new ClientConfiguration());
}
Elsewhere:
public class ClientConfiguration : EntityTypeConfiguration<Client>
{
public ClientConfiguration()
{
this.Property(p => p.Name).IsRequired();
}
}
来源:https://stackoverflow.com/questions/13000887/model-class-and-mapping