【问题标题】:Entity Framework data insert in foreign key实体框架数据插入外键
【发布时间】:2013-06-02 07:47:39
【问题描述】:

调用如下所示函数时出现错误:

存储更新、插入或删除语句影响了意外数量的行 (0)。自加载实体后,实体可能已被修改或删除。刷新 ObjectStateManager 条目。”

功能:

[HttpPost]
public ActionResult Index(InsertPo model)
{
        var context = new UsersContext();
        var po = new Po();
        var user = new User();
        po.PoId = 12;
        po.PoNumber = model.Po.PoNumber;
        po.Style = model.Po.Style;
        po.Quantity = model.Po.Quantity;
        po.Status = "hhh";
        po.OrderDate = Convert.ToDateTime("30-12-2011");
        po.ShipmentDate = Convert.ToDateTime("2-12-2011");
        po.ProductionRate = 10;
        po.UserId = 2;

        /*buyer.BuyerName = model.Buyer.BuyerName;*/
        /* buyer.BuyerId = 1;
         buyer.PoId = 10;*/
        context.Pos.Add(po);
        context.SaveChanges();
        return RedirectToAction("Index");
}

【问题讨论】:

  • 用户 ID=2 存在吗? ,检查键约束。 Po表上有一些触发器吗?试试 po.User= new user();
  • 您的视图中是否包含HiddenFor(model => model.Id)?当模型绑定器无法设置Id(或您拥有的任何[Key])时,我看到了一些问题。
  • 您是否覆盖了任何UsersContext 方法?

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


【解决方案1】:

尝试将此行放在您的 Action 方法之外。

    var context = new UsersContext();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-28
    • 2011-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    相关资源
    最近更新 更多