c# - 如何将 EF6 与 Database First 和现有 View 结合使用?

标签 c# entity-framework-6

我是一个 EF 菜鸟(任何版本),我的 Google-foo 没让我找到如何做到这一点。这让我觉得我一定做错了,但情况是这样的:

我绝对处于数据库优先的环境中,我们的编码人员不会更新架构。我也不喜欢“自动”代码生成,所以我一直远离设计器或 EF powertools(尽管我确实运行过它们只是为了看看它们的工作原理)。

为了学习,我将 Northwind 数据库导入了我的 LocalDB,以便在创建一些简单的 Web API 2 端点时可以使用。这一切都很顺利,因为我在 Northwind 中创建了 Employees、Shippers 和 Region 表的精简模型。 Region 特别有趣,因为它不是复数形式,而 EF 对此有疑问。无论如何,我做到了。

我现在的问题是;我想使用 View 而不是表作为我的源,而我正在做的任何事情似乎都不起作用。我尝试的是像设置表格一样设置它。但这会产生 ModelValidationException错误。我尝试查看设计器自动生成的代码,但一无所获。

我的模型:

//-- employee, shipper, & region work as expected
public class employee {
    public int EmployeeID { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
}

public class shipper {
    public int ShipperID { get; set; }
    public string CompanyName { get; set; }
    public string Phone { get; set; }
}

public class region {
    public int RegionID { get; set; }
    public string RegionDescription { get; set; }
}

//-- invoice is a view (actual viewname is 'Invoices')
//-- so i followed the same rules as i did for employee & shipper
//-- i have tried uppercase 'I' as well as a plural version of the model
public class invoice {
    public string CustomerID { get; set; }
    public string CustomerName { get; set; }
    public string Salesperson { get; set; }
    public int OrderID { get; set; }
    public int ProductID { get; set; }
    public string ProductName { get; set; }
}

我的上下文看起来像这样:

public class NorthwindDBContext : DbContext {
    public DbSet<Employee> Employees { get; set; }
    public DbSet<shipper> Shippers { get; set; }
    public DbSet<region> Regions { get; set; }
    public DbSet<Invoice> Invoices { get; set; } //-- offending line of code

    protected override void OnModelCreating(DbModelBuilder modelBuilder) {
        //--- fix for Region being singular instead of plural
        modelBuilder.Entity<region>().ToTable("Region");
    }
}

如果我注释掉 public DbSet<Invoice> Invoices { get; set; }在上下文中行一切正常。只需显示该行(即使我不引用 Invoices 属性)我就会收到 ModelValidationException无论如何使用上下文时出错。

谁能告诉我我做错了什么? 谢谢。

更新:我在我的一个 Controller 中试过这个,但我太菜鸟了,不知道这是否是正确的路径,尽管它在获取记录方面有效。

using (var dbContext = new NorthwindDBContext()) {
    return dbContext.Database.SqlQuery<Invoice>("select * from invoices").ToList();
}

最佳答案

代码优先约定将查找 IDInvoiceID 属性用作键。您的 Invoice 模型两者都没有,而其他模型则有。这是您的代码失败的具体原因。

不太具体的一个是您不能在 EF 中拥有缺少唯一键的实体。如果可以,让 View 定义一个键。否则,您仍然可以 work around the issue .

关于c# - 如何将 EF6 与 Database First 和现有 View 结合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19935536/

相关文章:

c# - 如何从其基类的实例创建新对象?

c# - 在 C# 中 try catch 的不同方法

c# - Entity Framework 6 mysql rowversion

c# - Entity Framework 更改父抽象对象的状态

mysql - EF6+MySQL - 在单个 SaveChanges 中插入 2 个相关对象时出错

c# - 如何使用带有 C# lambda 表达式的另一个表列中的 orderby

c# - c# 中可读性好的测试名称

c# - 使用来自 json 的变量 - Google play games quests

c# - Entity Framework 6 更新图

c# - 在 SelectMany LINQ to Entity Framework 中使用 PredicateBuilder