在插入

时间:2016-12-13 13:28:58

标签: asp.net-mvc entity-framework entity-framework-6

我使用EF6建立了一对一的关系。我的模型如下(删除了不必要的数据):

public class Property
{
    public int ID { get; set; }

    public virtual Facilities Facilities { get; set; }
}

和...

public class Facilities
{
    [Key, ForeignKey("Property")]
    public int PropertyID { get; set; }

    public virtual Property Property { get; set; }
}

我想要实现的是,当我创建一个'属性时,我还使用刚刚创建的PropertyID在facility表中创建一个条目。当我POST来创建一个属性时,没有任何反应(它没有重定向到索引,并且在任何一个表中都没有创建)。有没有错误可以帮助我理解发生了什么?我的控制器方法如下:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Create([Bind(Include = "ID,Name,Description,BedroomCount,BathroomCount,GuestCount,StreetAddress,ZipCode,CommunityID,PropertyTypeID")] Property property, Facilities facilities)
    {
        if (ModelState.IsValid)
        {
            property.UserID = User.Identity.GetUserId();
            property.DateCreated = DateTime.Now;
            property.Status = 1;
            db.Property.Add(property);
            await db.SaveChangesAsync();
            int lastPropertyID = db.Property.Max(item => item.ID);
            facilities.PropertyID = lastPropertyID;
            db.Facilities.Add(facilities);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        ViewBag.CommunityID = new SelectList(db.Community, "ID", "Name", property.CommunityID);
        ViewBag.PropertyTypeID = new SelectList(db.PropertyType, "ID", "Name", property.PropertyTypeID);
        return View(property);
    }

1 个答案:

答案 0 :(得分:1)

使用Entity Framework,您无需保存更改,然后手动获取ID,这是您唯一需要的:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "ID,Name,Description,BedroomCount,BathroomCount,GuestCount,StreetAddress,ZipCode,CommunityID,PropertyTypeID")] Property property, Facilities facilities)
{
    if (ModelState.IsValid)
    {
        property.UserID = User.Identity.GetUserId();
        property.DateCreated = DateTime.Now;
        property.Status = 1;
        db.Property.Add(property);
        facilities.Property = property;
        db.Facilities.Add(facilities);
        await db.SaveChangesAsync();
        return RedirectToAction("Index");
    }

    ViewBag.CommunityID = new SelectList(db.Community, "ID", "Name", property.CommunityID);
    ViewBag.PropertyTypeID = new SelectList(db.PropertyType, "ID", "Name", property.PropertyTypeID);
    return View(property);
}

调用SaveChanges时,所有ID都将自动从数据库中获取,并且实体将自动链接。致电SaveChanges后,您会注意到ID中的propertyPropertyID中的facilities已为您填充。