【问题标题】:How to avoid duplicate insert in Entity Framework 4.3.1如何避免实体框架 4.3.1 中的重复插入
【发布时间】:2014-07-26 03:33:25
【问题描述】:

我有一个使用代码优先方法创建的小模型 - 一个类 City,它只包含有关城市名称的信息。

public class City
{
    public City()
    {
        Posts = new List<Post>();
    }

    public City(string cityName)
    {
        Name = cityName;
    }

    public virtual ICollection<Post> Posts { get; private set; }
    public int Id { get; set; }
    public string Name { get; private set; }
}

Post 类表示邮政编码和城市参考的组合

public class Post
{
    public virtual City City { get; set; }        
    public int Id { get; set; }
    public string ZipCode { get; set; }        
}

两个实体的集合都在上下文中定义为它们的配置

public DbSet<City> Cities { get; set; }
public DbSet<Post> Posts { get; set; }

modelBuilder.Configurations.Add(new CityMap());
modelBuilder.Configurations.Add(new PostMap());


public class CityMap : EntityTypeConfiguration<City>
{
    public CityMap()
    {
        // Primary Key
        HasKey(t => t.Id);

        // Properties
        // Table & Column Mappings
        ToTable("City");
        Property(t => t.Id).HasColumnName("Id");
        Property(t => t.Name).HasColumnName("Name");
    }
}

public class PostMap : EntityTypeConfiguration<Post>
{
    public PostMap()
    {
        // Primary Key
        HasKey(t => t.Id);

        // Properties
        // Table & Column Mappings
        ToTable("Post");
        Property(t => t.Id).HasColumnName("Id");            
        Property(t => t.ZipCode).HasColumnName("ZipCode");

        // Relationships
        HasRequired(t => t.City)
        .WithMany(t => t.Posts)
        .Map(map=>map.MapKey("CityId"));
    }
}

我已经创建了一个类,用于使用静态方法处理这些对象,这些静态方法获取或创建对象并将它们返回给调用者。

private static City GetCity(string cityName)
{
        City city;

        using (var db = new DbContext())
        {
            city = db.Cities.SingleOrDefault(c => c.Name == cityName);

            if (city == null)
            {
                city = new City(cityName);
                db.Cities.Add(city);
                db.SaveChanges();                    
            }
        }

        return city;
    }

    private static Post GetPost(string zipCode, string cityName)
    {
        Post post;

        City city = GetCity(cityName);

        using (var db = new DbContext())
        {      
            post = db.Posts.SingleOrDefault(p => p.City.Id == city.Id && p.ZipCode == zipCode);
            if (post == null)
            {
                post = new Post { City = city, ZipCode = zipCode };

                // State of city is unchanged
                db.Posts.Add(post);

                // State of city is Added
                db.SaveChanges();
            }
        }

        return post;
    }

想象一下,我称之为方法

GetPost("11000","Prague");

方法GetCity被启动,如果不存在,方法创建一个city然后调用SaveChanges()方法。

如果我将返回的city 实体设置为新的Post 实例,实体框架会为相同的city 生成第二个插入。

如何避免这种行为?我只想插入新的 post 实体,其中引用了在上一步中创建或加载的 city

【问题讨论】:

    标签: entity-framework linq-to-entities duplicates entity-framework-4.3.1


    【解决方案1】:

    附加时需要设置你所在城市的State不变

    context.Entry(city).State = EntityState.Unchanged;
    

    【讨论】:

    • 谢谢 podiluska,我在我的代码中尝试过相同的方法,没有其他方法吗?
    • “保存悲伤并使用该外键” - 为什么实体框架将现有对象重新插入到我的数据库中? msdn.microsoft.com/en-us/magazine/dn166926.aspx
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多