DB Context如何工作

时间:2015-05-19 13:54:34

标签: entity-framework asp.net-mvc-5

真的坚持使用MVC应用程序。

我有这样的数据库上下文:

public class DataBaseContext : DbContext
{

    public DataBaseContext() : base("name = EIPInternalConnectionx")
    {

    }        
    public DbSet<LkUpGenderModel> vwLkUpGender { get; set; } 

    public DbSet<EditEmpModelView> vwEmployeeDetails { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        base.OnModelCreating(modelBuilder);
    }
}

当涉及到运行时并且运行控制器代码时:

,例如

return PartialView(db.vwEmployeeDetails.ToList());

我收到错误说

Invalid object name 'dbo.EditEmpModelView'.

我不想启用迁移或类似的东西来创建表dbo.EditEmpModelView'。我想查看Sql中名为vwEmployeeDetails的表,这是我认为我编码的。

有人可以告诉我我做错了什么,我对性别问题做了同样的事情,这样做有效,所以我完全糊涂了!

在global.asax文件中我有

Database.SetInitializer<DataBaseContext>(null);
Application_Start()

中的

1 个答案:

答案 0 :(得分:1)

正如我们在聊天室中讨论的那样,由于您使用视图映射到模型,因此您最好的方法是定义一系列DbConfigurations来覆盖默认的实体框架约定。类似于:

namespace DataAccess.DbConfigurations
{
public class EmployeeDetailsConfiguration : EntityTypeConfiguration<EditEmpModelView>
{
    public EmployeeDetailsConfiguration()
    {
        ToTable("vwEmployeeDetails");
        HasKey(ed => ed.EmployeeId);
    }
}
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new EmployeeDetailsConfiguration());
}