我一直在努力解决这个问题。我有一个模型和一个编辑视图模型,所以我可以让用户看到之前上传的图像并上传替换。一切正常,直到我到达db.Entry
部分。错误是:
实体类型EditCardViewModel不是当前上下文的模型的一部分。
如果我尝试将EditCardViewModel
添加到DbContext
,它需要一个密钥和一个表,这是不会发生的。 ViewModel只是一种传递数据的方法。从此ViewModel保存时,如何告诉它使用Cards上下文?
Controller Edit获取:
public ActionResult Edit(int id = 0)
{
Card card = db.Cards.Find(id);
ViewData["Abilities"] = card.CardAbilities.Select(a => a.AbilityID);
if (card == null)
{
return HttpNotFound();
}
var editview = new EditCardViewModel(card);
{
}
return View(editview);
}
Controller Edit Post:
[HttpPost]
public ActionResult Edit(EditCardViewModel card)
{
if (ModelState.IsValid)
{
if(card.ImageUpload != null)
{
string savedFileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Images");
savedFileName = Path.Combine(savedFileName, Path.GetFileName(card.ImageUpload.FileName));
card.ImageUpload.SaveAs(savedFileName);
card.Cards.ImageUrl = "\\Images\\" + Path.GetFileName(card.ImageUpload.FileName);
}
db.Entry(card).State = EntityState.Modified; //ERROR - Entity Type is not part of context
db.SaveChanges();
编辑ViewModel:
public class EditCardViewModel
{
public Card Cards { get; set; }
public HttpPostedFileBase ImageUpload { get; set; }
public IEnumerable<SelectListItem> Abilities { get; set; }
public int[] SelectedAbilities { get; set; }
public IEnumerable<SelectListItem> Rarities { get; set; }
public int SelectedRarities { get; set; }
public IEnumerable<SelectListItem> MainTypes { get; set; }
public int SelectedMainTypes { get; set; }
public IEnumerable<SelectListItem> SubTypes { get; set; }
public int SelectedSubTypes { get; set; }
public IEnumerable<SelectList> CardSets { get; set; }
public int SelectedCardSets { get; set; }
public Rarity Rarity { get; set; }
public MainType MainType { get; set; }
public SubType SubType { get; set; }
public CardSet CardSet { get; set; }
public EditCardViewModel() { } //NEEDED OR PARAMETERLESS CONSTRUCTOR ERROR
public EditCardViewModel(Card card) //NEEDED OR CANNOT PASS CARD MODEL
{
Cards = card;
}
}
答案 0 :(得分:0)
问题是实体框架无法识别您的视图模型 - 它不知道EditCardViewModel
是否代表Card
。从您的视图模型中可以清楚地知道您正在使用它做什么,但您需要创建一个新的Card
对象并使用它:
var newCard = new Card
{
Id = card.Id //for example
};
或者可能使用视图模型的Cards
属性,因为它的类型正确。