在Entity Framework添加新项目后获取ID

时间:2017-09-30 15:45:02

标签: asp.net-mvc entity-framework

我需要有关Entity Framework的帮助。

控制器:

public ActionResult Create([Bind(Prefix = "visit")] visit visit, [Bind(Prefix = "drugsEdition")]  IEnumerable<drugsEdition> drugsEdition, [Bind(Prefix = "accessoryEdition")]  IEnumerable<accessoryEdition> accessoryEdition, [Bind(Prefix = "servicesEdition")]  IEnumerable<servicesEdition> servicesEdition)
{
    Models.VisitDetails visitDetails = new Models.VisitDetails();
    visitDetails.visit = visit;

    if (ModelState.IsValid)
    {
        db.visit.Add(visit);

        if (drugsEdition != null)
        {
            foreach (var item in drugsEdition)
            {
                item.idVisit = visit.id;
                db.drugsEdition.Add(item);
            }
        }

        if (accessoryEdition != null)
        {
            foreach (var item in accessoryEdition)
            {
                item.idVisit = visit.id;
                db.accessoryEdition.Add(item);
            }
        }

        if (servicesEdition != null)
        {
            foreach (var item in servicesEdition)
            {
                item.idVisit = visit.id;
                db.servicesEdition.Add(item);
            }
        }

        db.SaveChanges();

        return RedirectToAction("Details", new { id = visit.id });
    }

    return View(visitDetails);
}

型号:

[Table("servicesEdition")]
public partial class servicesEdition
{
    public int id { get; set; }

    public int idService { get; set; }
    public int idVisit { get; set; }
    public double priceSell { get; set; }

    [ForeignKey("idService")]
    public virtual services services { get; set; }
}

在此代码中,我添加了对数据库的新访问,我希望在代码行id之后访问db.visit.Add (visit)。当我添加新的drugsEdition和新的accessoryEdition时,此代码是正确的并且添加了良好idVisit,但是当我添加servicesEdition idVisit = 0时为什么'servicesEdition'不会得到好的idVisit?

2 个答案:

答案 0 :(得分:0)

如果您添加类型为virtual的{​​{1}}导航属性,则EF会获得相应的访问ID,并在Visit方法调用中保存servicesEdition对象时将其填入。 / p>

我还将外键属性重命名为SaveChanges,以便参照完整性按约定(命名约定)工作,并且您不需要显式使用VisitId属性。我还建议你在编写C#类时使用PascalCasing(不一定需要你的代码才能工作)

ForeignKey

如果你不想像我上面描述的那样改变public partial class ServicesEdition { public int id { get; set; } public int idService { get; set; } public int VisitId { get; set; } public virtual Visit Visit { get; set; } public double priceSell { get; set; } [ForeignKey("idService")] public virtual services services { get; set; } } 实体定义,另一种选择是在你添加Visit实体后调用ServicesEdition方法然后你可以访问Id属性这一点。

SaveChanges()

答案 1 :(得分:0)

问题是viewBox在点击db.visit.Add(visit);

之前不会生成ID

您可以在db.SaveChanges();之后添加db.SaveChanges();。 或者你将保存为像Shyju解释的图表。