我正在使用ASP.NET MVC4构建一个带有代码优先数据迁移的应用程序。我有一个估计模型,客户模型,DbContext和我创建的视图模型。我希望在下拉列表中显示公司名称,公司名称与估计值相关联。我在两个模型中都有ClientId。我还创建了一个DbSet<>当查询它时,它没有用。
我尝试创建一个viewmodel,我认为我可以简单地查询并通过我的控制器显示。我没有运气让它上班。经过一天加上在这里和其他地方的观察,我没有想法。
如何查询/加入这两个模型,或查询viewmodel以获取与clientId关联的公司名称?谢谢你的帮助。
型号:
public class Estimates
{
[Key]
public int EstimateId { get; set; }
public int ClientId { get; set; }
public decimal EstimateAmount { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime EstimateDate { get; set; }
public string EstimateNotes { get; set; }
}
public class Clients
{
[Key]
public int ClientId { get; set; }
public string CompanyName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public ICollection<Estimates> Estimates { get; set; }
public ICollection<Contracts> Contracts { get; set; }
}
public class ClientEstimateViewModel
{
public Clients Clients { get; set; }
public Estimates Estimates { get; set; }
}
public class NovaDb : DbContext
{
public NovaDb(): base("DefaultConnection")
{
}
public DbSet<Clients> Clients { get; set; }
public DbSet<Estimates> Estimates { get; set; }
public DbSet<Contracts> Contracts { get; set; }
public DbSet<Invoices> Invoices { get; set; }
public DbSet<ClientEstimateViewModel> ClientViewModels { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}
控制器:
NovaDb _db = new NovaDb();
ClientEstimateViewModel ce = new ClientEstimateViewModel();
public ActionResult Index()
{
var model =
(from r in ce.Clients
join x in ce.Estimates
where
//var model =
// from r in _db.Clients
// orderby r.CompanyName ascending
// select r;
return View(model);
}
答案 0 :(得分:0)
因为您已经创建了客户与客户之间的关系。在模型中估算,您应该能够创建如下查询:
var query = from c in _db.clients
select new ClientEstimateViewModel
{
Clients = c,
Estimates = c.Estimates
}
虽然您必须更改模型,因此估算值为public List<Estimates> Estimates { get; set; }
这将为您提供ClientEstimateViewModel的集合,然后您可以将其传递给您的视图