ASP.net MVC 5 从视图模型编辑数据库中的条目错误 - 实体类型<myViewModel>不是当前上下文的模型的一部分



我有一个从ViewModel填充的编辑页面。此视图模型从几个模型(参与者、性别、国家/地区)中获取项目:

视图模型

namespace MVCManageParticipants.Models
{
public class ParticipantDetailsViewModel
{
public int Id { get; set; }
public int SiteId { get; set; }
public int Status { get; set; }
public string Gender { get; set; }
public string Title { get; set; }
public string Name { get; set; }
public string City { get; set; }
public int CountryId { get; set; }
public string Country { get; set; }
public string Postcode { get; set; }
public string Telephone { get; set; }
public string Notes { get; set; }
public IEnumerable<Country> Countries { get; set; }
}
}

IEnumerable 国家/地区返回了国家/地区的完整列表,并用数据库中的数据填充了一个下拉列表(这是我想扩展的城市、性别、状态的内容,但需要先让一个工作)。

附带问题:我如何执行此操作是填写数据库视图下拉列表的公认方式吗?

页面在 [HttpGet] 上填充良好,并将视图模型发送回视图。

[HttpGet] 控制器

var model = (from p in _db.Participants
where p.Id == id
select new ParticipantDetailsViewModel
{
Id = p.Id,
SiteId = p.SiteId,
Status = p.Status,
Gender = p.Gender.Name,
Title = p.Title,
Name = p.Name,
City = p.City.Name,
Country = p.Country.PrettyName,
CountryId = p.Country.Id,
Postcode = p.Postcode,
Telephone = p.Telephone,
Notes = p.Notes,
Countries = _db.Countrys.ToList()
}).FirstOrDefault();

[HttpPost] 控制器

public ActionResult Edit(ParticipantDetailsViewModel viewModel)
{
if (ModelState.IsValid)
{
_db.Entry(viewModel).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index", new { id = viewModel.Id });
}
return View(viewModel);
}

这让我在行_db上出错。条目(视图模型)。State = EntityState.Modified;:

An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: The entity type ParticipantDetailsViewModel is not part of the model for the current context.

参与者模型

public class Participant
{
public int Id { get; set; }
public int SiteId { get; set; }
public int Status { get; set; }
public Gender Gender { get; set; }
public string Title { get; set; }
public string Name { get; set; }
public City City { get; set; }
public Country Country { get; set; }
public string Postcode { get; set; }
public string Telephone { get; set; }
public string Notes { get; set; }
}

我这是因为我正在尝试更新视图模型而不是参与者模型?我是否应该创建一个新的参与者对象并以这种方式更新传入的数据?

ParticipantDetailsViewModel不是dbcontext的一部分,您需要使用 id 从数据库中获取Participant对象,并使用viewModel中的信息对其进行更新:

public ActionResult Edit(ParticipantDetailsViewModel viewModel)
{
if (ModelState.IsValid)
{
var participant = _db.Participants.FirstOrDefault(p => p.Id == viewModel.Id);
//set all properties whith new values
participant.SiteId = viewModel.SiteId
_db.Entry(participant).State = EntityState.Modified;
_db.SaveChanges();
return RedirectToAction("Index", new { id = viewModel.Id });
}
return View(viewModel);
}

最新更新