gpt4 book ai didi

c# - 将linq查询结果存储在Model中

转载 作者:行者123 更新时间:2023-11-30 13:31:41 26 4
gpt4 key购买 nike

我正在尝试查询数据库并将这些结果存储在模型中,其中一列是数字列,一列是字符串数据:

型号:

using System.Data.Entity;

namespace Portal.Models
{
public class CompanyListId
{
public int Id { get; set; }
public string CompanyName { get; set; }
}

public class CompanyListIdDbContext : DbContext
{
public DbSet<CompanyListId> Contacts { get; set; }
}
}

Controller :

    public PartialViewResult SelectCompanyFromDropdown()
{
using (var dc = new CompanyListIdDbContext())
{
var content = from p in db.Companies
select new { p.CoId, p.CompanyName };
}
//I want to set Models ID = to each instance of coid
//Set Models CompanyName to each instance of companyname

return PartialView();

}

我不确定从这里去哪里,我正在尝试从这个模型中下拉。

我将我的代码块更新为:

public PartialViewResult SelectCompanyFromDropdown()
{
using (var dc = new CompanyListIdDbContext())
{
var content = from p in db.Companies
select new CompanyListId
{
Id = p.CoId,
CompanyName = p.CompanyName
};
return PartialView(content.ToList());//giving an error
}
}

我的观点是:

@model Portal.Models.CompanyListId

@Html.DropDownListFor(m => m.CompanyName, Model.CompanyName)

这似乎也行不通,我需要从我认为的操作中返回我的模型,这样 View 才能正确使用数据。

最佳答案

您应该将结果投影到您的类CompanyListId

var content = from p in db.Companies
select new CompanyListId
{
Id = p.CoId,
CompanyName = p.CompanyName
};

编辑:

我不确定错误,但你可以尝试:

public PartialViewResult SelectCompanyFromDropdown()
{
List<CompanyListId> content = null;
using (var dc = new CompanyListIdDbContext())
{
content = (from p in db.Companies
select new CompanyListId
{
Id = p.CoId,
CompanyName = p.CompanyName
}).ToList();
}
return PartialView(content);
}

关于c# - 将linq查询结果存储在Model中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19145400/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com