Jak uniknąć duplikowania wstawki w Entity Framework 4.3.1
Mam mały model utworzony przy użyciu podejścia opartego na kodowaniu - klasyCity
który zawiera tylko informacje o nazwie miasta.
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; }
}
A Post
klasa reprezentuje połączenie kodu pocztowego i odniesienia do miasta
public class Post
{
public virtual City City { get; set; }
public int Id { get; set; }
public string ZipCode { get; set; }
}
obie jednostki mają swoje zestawy zdefiniowane w kontekście jako ich konfiguracje
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"));
}
}
Stworzyłem klasę do manipulowania tymi obiektami za pomocą metod statycznych, które pobierają lub tworzą obiekty i zwracają je do wywołującego.
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;
}
Wyobraź sobie, że dzwonię metodą
GetPost("11000","Prague");
metodaGetCity
jest uruchamiany, a jeśli nie istnieje, metoda tworzycity
a następnie wywołujeSaveChanges()
metoda.
Jeśli ustawię, wrócęcity
podmiot do nowegoPost
instancja Entity Framework generuje drugą wstawkę dla tego samegocity
.
Jak mogę uniknąć tego zachowania? Chcę tylko wstawić nowypost
podmiot z odniesieniemcity
utworzone lub załadowane w poprzednim kroku.