entity-framework - 如何创建通用的 EF Insert 方法?

标签 entity-framework

我想创建一个通用 C# 类,该类的方法将使用 Entity Framework 向数据库中添加一行。

我有一个名为 Address 的表。我编写了以下代码来向数据库添加地址:

public class AddressExchange
{
    public int Insert(Address address)
    {
        using (var db = new DemoWebEntities())
        {
            //db.AddObject("Address", address);
            db.Addresses.AddObject(address);
            db.SaveChanges();
            return address.Id;
        }
    }
}

我想编写一个通用类来为我的 EDMX 中的任何 实体执行此操作。我认为它应该看起来像这样:

public class EntityExchange<T, KeyType>
{
    public KeyType Insert(T t)
    {
        using (var db = new DemoWebEntities())
        {
            // The entity set name might be wrong.
            db.AddObject(typeof(T).Name, t);                

            // EF doesn't know what the primary key is.
            return t.Id;
        }
    }
}

我觉得可能可以使用AddObject方法将对象添加到数据库中,但是entityset名称不一定要和类型名称一样,尤其是已经复数的情况下!

我也想把主键返回给调用者,但是我不知道怎么判断哪个字段包含主键。

最佳答案

我在通用存储库中有一个通用的 InsertOrUpdate 方法,该方法还可以确保创建代理。 (代理需要支持延迟加载,如果您使用“new”创建实体,则不会创建代理)。见问题here

public class RepositoryBase<T> : IRepository<T> where T : ModelBase
{
    public virtual T InsertOrUpdate(T e)
    {
        DbSet<T> dbSet = context.Set<T>();

        //Generate a proxy type to support lazy loading
        T instance = dbSet.Create();

        DbEntityEntry<T> entry;
        if (e.GetType().Equals(instance.GetType()))
        {
            //The entity being added is already a proxy type that 
            //supports lazy loading just get the context entry
            entry = context.Entry(e);
        }
        else
        {
            //The entity being added has been created using the "new" operator. 
            //Attach the proxy
            //Need to set the ID before attaching or we get 
            //The property 'ID' is part of the object's key 
            //information and cannot be modified when we call SetValues
            instance.ID = e.ID;
            entry = context.Entry(instance);
            dbSet.Attach(instance);

            //and set it's values to those of the entity
            entry.CurrentValues.SetValues(e);
            e = instance;
        }

        entry.State = e.ID == default(int) ?
                                EntityState.Added :
                                EntityState.Modified;

        return e;
    }
}

public abstract class ModelBase
{
    public int ID { get; set; }
}

请注意,所有模型都继承了 ModelBase 以便处理 ID 问题,并且我返回实体而不仅仅是 ID。这可能不是绝对必要的,因为传入了对实体的引用,并且 EF 无论如何都会对 ID 执行修复,因此您始终可以从传入的引用访问它。

关于entity-framework - 如何创建通用的 EF Insert 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17748956/

相关文章:

javascript - OData $top 和 PageSize 对 Web API 性能没有影响

sql-server - 为什么这个 EF 查询需要这么长时间?

entity-framework - 如何支持 OData 查询语法但返回非 Edm 模型

asp.net-mvc - ApplicationDbContext - 它在项目中所属的位置

c# - .NET 标准的 System.Data.SqlClient 出错

entity-framework - EF5 Code First 标识列错误

多对多 EF Code First 对象中带有 where 子句的 Linq

c# - 将包含 IN 语句的 SQL 转换为可链接的 LINQ

asp.net-mvc - AspNet.Identity 自定义用户和自定义角色应该很简单;我错过了什么?

c# - 使用 LINQ 包含嵌套子级的嵌套