获取实体的状态都会添加主键 [英] Obtain primary key of entity whose state is Added

查看:172
本文介绍了获取实体的状态都会添加主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

我实施的UnitOfWork并为我的Web应用程序库的风格数据访问层。我希望审核使用自定义表我已经更改了数​​据库。当新的项目被添加到上下文时出现问题。该项目被添加到上下文,但的SaveChanges()方法尚未调用,所以该实体还处于添加状态。这意味着,在没有被分配一个主键,这意味着我不能创建一个审计记录,并要求的SaveChanges()从资源库将违反库代码风格。有没有办法让一个实体的主键中加入的状态?

尝试性解决方案

这是我能想到的唯一解决方法是使用随机的GUID,以便客户端可以生成它们。我有点犹豫,因为我听说,用随机的GUID作为标识字段可能是昂贵的。

code

  //方法在我的仓库类
公共无效插入(T实体)
{
    //添加实体上下文
    dbSet.Add(实体);

    审计署的审计=新的审计
    {
        创建= DateTime.Now,
        的PrimaryKey = entity.Key,//这不是设置,因为实体的状态仍增加
    };

    Context.Audits.Add(审计);
}
 

解决方案

简单的答案是,你不能在分布式环境中做到这一点。你不能保证,一旦项目被永久存储的ID将是相同的。

使用生成的客户端的GUID确实解决了问题。这是我通常采取的办法,但我们不要开始的辩论!你会发现大部分的结果是50/50。两者都有优点和缺点。对于您的情况,它的工作原理!

Problem

I am implementing a UnitOfWork and a Repository style data access layer for my web application. I want to audit changes to the database using a custom table I have made. The problem occurs when a new item is added to the context. The item is added to the context, however SaveChanges() method has not been called so the entity is still in the Added state. This means that is has not been assigned a primary key, which means I can not create an audit record and calling SaveChanges() from the repository would violate the repository coding style. Is there a way to get the primary key of an entity in the added state?

Attempted Solution

The only solution that I can think of is to use random GUIDs so that the client can generate them. I am a little hesitant because I have heard that using random GUIDs as the identity field can be costly.

Code

//Method in my repository class
public void Insert(T entity)
{
    //Adds the entity the context
    dbSet.Add(entity);

    Audit audit= new Audit 
    {
        Created = DateTime.Now,
        PrimaryKey = entity.Key, //This is not set because the State of the entity is still Added
    };

    Context.Audits.Add(audit);
}

解决方案

Simple answer is you can't do this in a distributed environment. You can't guarantee that the ID will be the same once the item is persisted.

Using client generated GUIDs does solve the problem. This is the approach I normally take, though let's not start a debate on that! You will mostly find the outcome is 50/50. Both have pros and cons. For your scenario, it works!

这篇关于获取实体的状态都会添加主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆