您将如何编写LINQ to SQL的Upsert? [英] How would you write an Upsert for LINQ to SQL?

查看:49
本文介绍了您将如何编写LINQ to SQL的Upsert?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我想为LINQ to SQL编写一个通用的Upsert函数,而在构思如何实现时遇到了一些麻烦.我希望它能像这样工作:

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:

var db = new DataContext();
db.Customers.UpsertOnSubmit(customer);

因此,它在某种程度上必须是通用的,我想是对Table的扩展方法.在确定基础表的主键方面,我已经走得很远了:

So it would have to be generic in some way and I guess and extension method on Table. I've been able to get this far in determining the primary key of the underlying table:

var context = source.Context;
var table = context.Mapping.GetTable(source.GetType());
var primaryMember = table.RowType.DataMembers.SingleOrDefault(m => m.IsPrimaryKey);

我认为有必要使它组成一个查询,以告知该项目是否已在数据库中,但是我目前还不知道该怎么处理.

I'm assuming it will be necessary to have this to compose a query to tell if the item is in the DB already or not but I don't really know what to do with it at this point.

推荐答案

我做了类似的事情,但是使用了不同的方法.每个实体都实现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.

这篇关于您将如何编写LINQ to SQL的Upsert?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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