3

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

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

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

我现在的麻烦是;我想使用视图而不是表格作为我的来源,而无论我在做什么似乎都不起作用。我尝试的是设置它,就像我做桌子一样。但这会产生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,无论如何我在使用上下文时都会收到错误消息。

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

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

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

1 回答 1

0

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

不太具体的是,您不能在 EF 中拥有缺少唯一键的实体。如果可以,让视图定义一个键。否则,您仍然可以解决该问题

于 2013-11-12T19:56:06.437 回答