当新行插入表时,为什么我得到ID = 0?

时间:2017-07-19 10:21:44

标签: c# entity-framework

我使用Entity frameWork将新行保存到我的数据库中。

我创建了向表中插入新对象的方法。对象被添加到表中但方法总是返回0。而我期望新的Id

以下是方法:

private int SaveVectorLayer(VVectorLayer layer)
{
    if (layer == null) return 0;

    Data.VectorLayer vectorLayer;
    if (layer.Id == 0)
    {
        vectorLayer = new Data.VectorLayer();
        _context.Entry(vectorLayer).State = EntityState.Added;
    }
    else
    {
        vectorLayer = _context.VectorLayers.Find(layer.Id);
        if (vectorLayer == null) throw new ObjectNotFoundException(string.Format("Layer with id={0} not found!", layer.Id));
    }
    vectorLayer.Title = layer.Title;
    if (layer.Style != null) layer.Style.SaveStyle(vectorLayer);
    vectorLayer.MinScale = layer.MinScale;
    vectorLayer.MaxScale = layer.MaxScale;
    vectorLayer.GeomType = layer.GeomType ?? "Point";

    _context.SaveChanges();

    return layer.Id;
}

知道为什么返回Id总是0?

4 个答案:

答案 0 :(得分:3)

您的退货单应为vectorLayer.Id。 您当前正在返回数据库中未找到且Id为0的对象的Id

另外,关于以下代码:

vectorLayer.Title = layer.Title;
if (layer.Style != null) layer.Style.SaveStyle(vectorLayer);
vectorLayer.MinScale = layer.MinScale;
vectorLayer.MaxScale = layer.MaxScale;
vectorLayer.GeomType = layer.GeomType ?? "Point";

考虑使用类似克隆的方法或Copy Constructor封装它。

答案 1 :(得分:1)

您需要返回vectorLayer.Id。你永远不会在任何地方设置layer.IdvectorLayer是您创建并添加到数据库的内容。

答案 2 :(得分:1)

此代码存在一些问题。

  1. 正如其他人注意到的那样,您正在保存vectorLayer,而不是layer。如果要返回ID,则应返回vectorLayer.Id
  2. 如果输入丢失,您的代码将返回0

    if (layer == null) return 0;
    

    那不是个好主意。这意味着您无法区分实际的0和无效的输入。如果这是意外的,则抛出异常。如果是,则将方法更改为bool TrySaveVectorLayer(layer,out int id)或(bool ok,int id)SaveVectorLayer(layer)`。

  3. 最糟糕的情况是,返回否定数字或某些明显无效的值,因此您至少知道发生了什么。

    它可能完全不同于其他内容,例如不会自动生成的ID字段,例如通过IDENTITY()或SEQUENCE

答案 3 :(得分:0)

return layer.Id; //this id is of wrong object

以上行返回 VVectorLayer 的ID。但实际上您想要返回插入数据行的ID。那将是实体vectorLayer中的Id。

所以你必须返回vectorLayer.Id;