我正在开发一个C#MVC 4互联网应用程序,我有一个关于将项目添加到列表的问题。
这是我的班级代码:
public class MapLocationCompany
{
public MapLocationCompany()
{
MapLocationList = new List<MapLocation>();
}
[Key]
public int id { get; set; }
public List<MapLocation> MapLocationList { get; set; }
}
public class MapLocationCompanyContext : DbContext
{
public DbSet<MapLocationCompany> MapLocationCompanies { get; set; }
}
我正在创建一个MapLocation
对象,以添加到MapLocationList
类中的MapLocationCompany
。
这是我的代码:
private MapLocationCompanyContext mlcc = new MapLocationCompanyContext();
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(int id, MapLocation maplocation)
{
if (ModelState.IsValid)
{
MapLocationCompany mapLocationCompany = new MapLocationCompany();
mapLocationCompany = cs.getMapLocationCompany(id);
mapLocationCompany.MapLocationList.Add(maplocation);
mlcc.SaveChanges();
return RedirectToAction("MapLocations", "Company", new { id = id });
}
return View(maplocation);
}
这是cs.getMapLocationCompany
函数,它位于不同的类
public MapLocationCompany getMapLocationCompany(int id)
{
return db.MapLocationCompanies.Where(c => c.id == id).FirstOrDefault();
}
db是MapLocationCompanyContext
对象。
maplocation
函数中的Create
对象未存储在数据库中。
我可以帮助您使用此代码吗?
提前致谢
修改
我可以帮助您使用Context吗?
将MapLocation对象添加到列表中以下是我目前正在处理的代码:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(int id, MapLocation maplocation)
{
if (ModelState.IsValid)
{
MapLocationCompany mapLocationCompany = new MapLocationCompany();
mapLocationCompany = cs.getMapLocationCompany(id);
mlcc.MapLocationCompanies.Where(c => c.id == id).FirstOrDefault().Add(maplocation);
mlcc.SaveChanges();
return RedirectToAction("MapLocations", "Company", new { id = id });
}
return View(maplocation);
}
这是我得到的错误:
'CanFindLocation.Classes.MapLocationCompany'不包含'Add'的定义,也没有扩展方法'Add'接受'CanFindLocation.Classes.MapLocationCompany'类型的第一个参数可以找到
如何知道MapLocationCompany
?
答案 0 :(得分:0)
您正尝试在此MapLocation
对象中直接添加MapLocationCompany
:
mlcc.MapLocationCompanies.Where(c => c.id == id).FirstOrDefault().Add(maplocation);
这是不正确的。您想将其添加到MapLocationList
对象的MapLocationCompany
属性中。这可能会更清楚:
var company = mlcc.MapLocationCompanies.Where(c => c.id == id).FirstOrDefault();
if (company != null) {
company.MapLocationList.Add(mapLocation);
}