1

my Model Entity FrameWork :

public partial class T02
{
    public long ID { get; set; }
    public int F01 { get; set; }
}

Table : T02

------------------------
id[Key,identity]      F01
------------------------
1       a
2       b

==================================================== i have a button > Code

    public void Button_Click(object Sender, EventArgs e)
    {
        T02 T1 = new T02 { ID = 1, F01 = "x" };
        T02 T2 = new T02 { ID = 2, F01 = "y" };
        T02 T3 = new T02 { ID = 0, F01 = "g" };
        T02 T4 = new T02 { ID = 0, F01 = "h" };

        // How ID > 1 2 Update in Table & 
        // because not in table, > g , h > automatic add to Table 
        // ???
    }

my problem is : i not ontime update and if T02.ID not on the table automatic added..

Is it possible that I do added to table Records Without id and i do Update Records With id

i worked c#.NET 4.5 . Thanks

4

1 回答 1

0

将此方法添加到您的Context类中:

protected virtual void InsertOrUpdate<T>(T entity, long id)
{
    if (id == default(int))
        this.Set<T>().Add(entity);
    else
        this.Entry(entity).State = EntityState.Modified;
}

可以这样使用:

public void Button_Click(object Sender, EventArgs e)
{
    T02 T1 = new T02 { ID = 1, F01 = "x" };
    T02 T2 = new T02 { ID = 2, F01 = "y" };
    T02 T3 = new T02 { ID = 0, F01 = "g" };
    T02 T4 = new T02 { ID = 0, F01 = "h" };

    using(var context = new MyDbContext())
    {
        context.InsertOrUpdate(T1, T1.ID);
        context.InsertOrUpdate(T2, T2.ID);
        context.InsertOrUpdate(T3, T3.ID);
        context.InsertOrUpdate(T4, T4.ID);
    }
}

一旦这工作正常,您可以考虑在所有公开ID属性的 POCO 类中实现一个标准接口,这样您就不必再传递给ID该方法:

public interface IId
{
    long ID { get; }
}

public partial class T02 : IId
{
    public long ID { get; set; }
    public int F01 { get; set; }
}

这为您提供了一种更简洁的方法Context

protected virtual void InsertOrUpdate<T>(T entity) where T : IId
{
    if (entity.ID == default(int))
        this.Set<T>().Add(entity);
    else
        this.Entry(entity).State = EntityState.Modified;
}
于 2013-09-03T09:53:02.827 回答