简体   繁体   English

EF在编辑时不保存虚拟属性

[英]EF not saving virtual properties when editing

I have a model Team which looks like this: 我有一个模型Team ,看起来像这样:

public class Team
{
    [Key]
    public int TeamId { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
    public virtual Group Group { get; set; }
}

I have a method to Edit it: 我有一种方法来Edit它:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Team team)
{
    using (var db = new DbConnection())
    {
        if (ModelState.IsValid)
        {
            db.Entry(team).State = EntityState.Modified;

            db.Groups.Attach(team.Group);

            db.SaveChanges();
        }

        return PartialView(team);
    }
}

However it is not saving the change to the Group column. 但是,它没有将更改保存到“ Group列中。 Meanwhile Create method does work although I see no difference between them: 虽然我看不出它们之间的区别,但是Create方法确实可以工作:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Team team)
{
    using (var db = new DbConnection())
    {                
        if (ModelState.IsValid)
        {
            db.Groups.Attach(team.Group);

            db.Teams.Add(team);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return PartialView(team);
    }
}

The values for the Group come the same in both methods. 两种方法中Group的值都相同。 I bring the values to the form like this (again, same thing for both): 我将值带入这样的形式(同样,两者相同):

ViewBag.Groups = db.Groups.ToList().Select(g => new SelectListItem()
{
    Text = g.Code,
    Value = g.GroupId.ToString(),
    Selected = false
}).ToList(); 

and use them like this: 并像这样使用它们:

@Html.DropDownListFor(model => model.Group.GroupId, (List<SelectListItem>)ViewBag.Groups)

Can someone please explain what the difference between the two methods is (in terms of one saving Group and other - not)? 有人可以解释这两种方法之间的区别吗(就一个保存Group而言,而另一种则不是)?

PS Using both the latest MVC and EF. PS同时使用最新的MVC和EF。

Apparently it is a must (?) (at least I couldn't find anything better) to add a field matching the type of the Group in order to be able to easily save. 显然,必须添加一个与Group类型匹配的字段,以便能够轻松保存,这是必须(?)(至少我找不到更好的选择了)。 No need to attach anything this way. 无需以这种方式附加任何内容。 Now my model looks like: 现在我的模型如下:

public class Team
{
    [Key]
    public int TeamId { get; set; }
    public string Name { get; set; }
    public string Code { get; set; }
    public int? GroupId { get; set; }
    public virtual Group Group { get; set; }
}

and my Save and Create methods got this line: 我的SaveCreate方法得到了这一行:

db.Groups.Attach(team.Group);

removed. 删除。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM