【发布时间】:2018-12-23 13:34:30
【问题描述】:
我有 asp.net web api 应用程序。我在数据库中有一个表 Companies,它有两个字段:id 和 description。最近我更新了数据库并添加了一个名为 CustomerID 的新列。之后,当我尝试调用 getCompanies 时
private readonly BackendContext _context;
public CompaniesController(BackendContext context)
{
_context = context;
}
// GET: api/Companies
[HttpGet]
public IEnumerable<Company> GetCompanies()
{
return _context.Companies;
}
我明白了
我认为控制器试图返回旧的公司模型,但无法实现它,因为它现在不存在,但我不知道如何解决这个问题,尽管控制器应该返回更新的模型。也许我应该以某种方式重建应用程序以使其使用更新的版本?
附加代码: 上下文
public class BackendContext : Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityDbContext<IdentityUser>//DbContext
{
public BackendContext(DbContextOptions<BackendContext> options) : base(options) { }
public DbSet<Company> Companies { get; set; }
public DbSet<CompanyToProduct> CompanyToProducts { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Vendor> Vendors { get; set; }
public DbSet<VendorToProduct> VendorToProducts { get; set; }
public DbSet<Invoice> Invoices { get; set; }
public DbSet<InvoiceItem> InvoiceItems { get; set; }
}
型号
public class Company
{
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int CustomerID { get; set; }
public virtual Customer Customer { get; set; }
public virtual ICollection<CompanyToProduct> CompaniesToProducts { get; set; }
public virtual ICollection<Invoice> Invoices { get; set; }
}
更新 我在表格中添加了一些值,并得到了第一家公司的回复:
[{"id":1,"name":"Google","description":"free food","customerID":6,"customer":null,"companiesToProducts":null,"invoices":null}
但我也得到了表中未指定的字段:客户、公司到产品、发票。 Invoices 和 CompaniesToProducts 是我数据库中的表,我不知道客户指的是什么。我还应该提到这些表是通过外键连接的。
【问题讨论】:
-
这可能是相关的:stackoverflow.com/questions/44322809/… 如果您的模型有循环引用,它可能无法序列化。如果将
.ToList()附加到要返回的集合中会发生什么?或者使用.Select()将其投影为匿名类型以指定您想要的确切属性? -
@David 当我这样做时收到服务器错误:return _context.Companies.ToList();像相关问题中的启动修改不会改变
-
在搞乱这家初创公司之前,我建议将模型投影到特定的值子集中。毕竟,如果这些模型引用了其他模型,哪些模型引用了其他模型等等,那么您真的希望在这个 API 调用中返回 那么多 数据吗?你具体要返回的字段是什么?
-
@David 我只想返回有关公司的数据,但控制器还返回其他字段,例如客户、companyToProducts、发票(我已经更新了帖子),这些字段在数据库修改之前不在响应中。它也只返回第一家公司。我应该编辑以前正确返回的数据而不添加 ToList() 等。
标签: c# asp.net database asp.net-web-api connection-reset