Use DbContext.Model to configure the edm model.
使用 DbContext 上配置的模型(Microsoft.EntityFrameworkCore.Metadata.IModel 的示例)自动配置 OData 模型中的复杂类型和实体类型。
- Step 1: Configure your Entity Framework Core Model with
OnModelCreating.
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}
// ...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// ...
}
}- Step 2: Register your
DbContextand then useEdmModel.CreateConventionFactory()static method to create aIEdmModelfactory.
public void ConfigureServices(IServiceCollection services)
{
void UseSqlServer(DbContextOptionsBuilder optionsBuilder) =>
optionsBuilder.UseSqlServer(Configuration.GetConnectionString("ApplicationDb"));
services.AddDbContext<ApplicationDbContext>(UseSqlServer);
// ...
} - Step 3: Use
EdmModel.CreateConventionFactory()static method to create aIEdmModelfactory, and then callConfigureWithDbContextorConfigureWithEntityFrameeworkModel.
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddController().AddOData(options => options
.AddRouteComponents("odata", CreateEdmModel(UseSqlServer)));
}
private static IEdmModel CreateEdmModel(Action<DbContextOptionsBuilder> optionsAction)
{
return EdmModel.CreateConventionFactory()
.ConfigureWithDbContext<ApplicationDbContext>(optionsAction)
.Configure(builder =>
{
// Additional configuration for the edm model.
}).CreateEdmModel();
}