且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

您将如何编写LINQ to SQL的Upsert?

更新时间:2023-02-09 23:35:12

我做了类似的事情,但是使用了不同的方法.每个实体都实现IEntity. IEntity的属性之一是对象是新对象还是现有对象的状态.然后,我为每个实体实现该功能,例如:

I do something similar, but with a different approach. Every entity implements IEntity. One of the properties of IEntity is a state if the object is new or existing. I then implement that for each entity, like:

public EntityState EntityState
{
    get
    {
        if (_Id > 0)
            return EntityState.Exisiting;
        else
            return EntityState.New;
    }
}

然后,通用Upsert可能是(在通用存储库类型类上):

Then, a generic Upsert could be (on a generic repository type class):

public virtual void Upsert<Ta>(Ta entity)
    where Ta: class
{
    if (!(entity is IEntity))
        throw new Exception("T must be of type IEntity");

    if (((IEntity)entity).EntityState == EntityState.Exisiting)
        GetTable<Ta>().Attach(entity, true);
    else
        GetTable<Ta>().InsertOnSubmit(entity);
}

private System.Data.Linq.Table<Ta> GetTable<Ta>()
    where Ta: class
{
    return _dataContext.Context.GetTable<Ta>();
}

如果您是从另一个数据上下文附加的,还请确保您的对象上有时间戳记.

If your attaching from another datacontext, also make sure you have a timestamp on your objects.