如何避免在实体框架4.3.1重复插入(How to avoid duplicate insert i

2019-07-03 16:02发布

我使用代码优先方法创建了一个小模型-一类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创建或在上一步中加载。

Answer 1:

您需要设置的State的城市,当你将其连接到不变

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


文章来源: How to avoid duplicate insert in Entity Framework 4.3.1