使用defaultValue时,如何在Entity框架中获取插入实体的Id?

时间:2012-09-05 11:08:29

标签: c# entity-framework entity

有没有办法用defaultValue发送属性但是用数据库计算结果更新它?数据库中有一个触发器,对于输入-1,触发一个计算新值的过程。如何获得价值?

<Property Name="ID" Type="int" Nullable="false" StoreGeneratedPattern="None" DefaultValue="-1" />

var x = new Stuff();
db.Stuff.AddObject(x);
db.SaveChanges();
return x.ID //gives -1, but the computed value should be different.

6 个答案:

答案 0 :(得分:15)

您需要在savechanges之后重新加载实体。因为它已被EF无法跟踪的数据库触发器更改。所以我们需要再次从数据库重新加载实体,

var x = new Stuff();
db.Stuff.AddObject(x);
db.SaveChanges();
db.Entry(x).GetDatabaseValues();

return x.ID;

答案 1 :(得分:2)

如果您使用的是EF核心,则可能是这样:

 public int CreateMyEntity(MyEntityType myEntity)
 {
      Microsoft.EntityFrameworkCore.ChangeTracking.EntityEntry<MyEntityType> created = _context.MyEntityType.Add(myEntity);
      _context.SaveChanges()
      return created.Entity.Id;
  }

答案 2 :(得分:1)

我正在使用数据传输对象(DTO)从前端隐藏数据层的详细信息-然后将其中的值分配给db对象。我的CustomerId是一个标识,在调用SaveChanges()后会自动刷新该标识。不需要其他方法调用。而且由于“客户”是ref对象,因此它会传播到前端。

public static void Add(DTO.Customer customer)
{
    MyEntities db = new MyEntities();

    var customerToAdd = new MyEntities.Data.Customer { Address = customer.Address, FirstName = customer.FirstName, LastName = customer.LastName, etc... };
    db.Customers.Add(customerToAdd);

    db.SaveChanges();
    customer.CustomerId = customerToAdd.CustomerId;
}

答案 3 :(得分:0)

我遇到了同样的问题,在调用SaveChanges后我的密钥不会更新,而context.Entry(newObj).GetDatabaseValues()只会返回null。

在我的情况下,在EntityFramework模型中将StoreGeneratedPattern设置为Identity(在密钥上)会导致密钥在调用SaveChanges后更新。

答案 4 :(得分:0)

使用(var context = new EntityContext()) {

<div><input type="text" id="search" onchange="tagsearch(this.value)"></div>
<div class="row" id="add">
  <span class="border">
 <figure class="figure">
 <a href="#"><img src="https://picsum.photos/id/437/200/200" class="figure-img img-fluid rounded" alt=""></a> 
 <figcaption class="figure-caption">CLUB 5</figcaption>
 </figure>
 </span>
  <span class="border">
 <figure class="figure">
 <a href="#"><img src="https://picsum.photos/id/437/200/200" class="figure-img img-fluid rounded" alt=""></a> 
 <figcaption class="figure-caption">CLUB 6</figcaption>
 </figure>
 </span>
  <span class="border">
 <figure class="figure">
 <a href="#"><img src="https://picsum.photos/id/437/200/200" class="figure-img img-fluid rounded" alt=""></a> 
 <figcaption class="figure-caption">CLUB 7</figcaption>
 </figure>
 </span>
  <span class="border">
 <figure class="figure">
 <a href="#"><img src="https://picsum.photos/id/437/200/200" class="figure-img img-fluid rounded" alt=""></a> 
 <figcaption class="figure-caption">CLUB 8</figcaption>
 </figure>
 </span>
</div>



<div id="add"></div>

}

答案 5 :(得分:-2)

   using (var context = new MyContext())
   {
       context.MyEntities.AddObject(newObject);
       context.SaveChanges();

       int id  = newObject.Id; // Will give u the autoincremented ID
   }