How would you write an Upsert for LINQ to SQL?

前端 未结 2 766
时光取名叫无心
时光取名叫无心 2020-12-09 04:09

So I\'d like to write a generic Upsert function for LINQ to SQL and I\'m having some trouble conceptualizing how to do it. I\'d like it to work something like this:

2条回答
  •  难免孤独
    2020-12-09 04:22

    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;
        }
    }
    

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

    public virtual void Upsert(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().Attach(entity, true);
        else
            GetTable().InsertOnSubmit(entity);
    }
    
    private System.Data.Linq.Table GetTable()
        where Ta: class
    {
        return _dataContext.Context.GetTable();
    }
    

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

提交回复
热议问题