I have a small model created using the code of the first approach - a class Citythat contains only information about the name of the 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; }
}
Class A Postis a combination of a zip code and a city link
public class Post
{
public virtual City City { get; set; }
public int Id { get; set; }
public string ZipCode { get; set; }
}
both objects have their sets defined in context, as their configuration
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()
{
HasKey(t => t.Id);
ToTable("City");
Property(t => t.Id).HasColumnName("Id");
Property(t => t.Name).HasColumnName("Name");
}
}
public class PostMap : EntityTypeConfiguration<Post>
{
public PostMap()
{
HasKey(t => t.Id);
ToTable("Post");
Property(t => t.Id).HasColumnName("Id");
Property(t => t.ZipCode).HasColumnName("ZipCode");
HasRequired(t => t.City)
.WithMany(t => t.Posts)
.Map(map=>map.MapKey("CityId"));
}
}
I created a class to manipulate these objects with static methods that receive or create objects and return them to the caller.
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 };
db.Posts.Add(post);
db.SaveChanges();
}
}
return post;
}
Imagine calling a method
GetPost("11000","Prague");
the method is GetCitystarted, and if it does not exist, the method creates Cityand then calls the method SaveChanges().
City Post, Entity Framework City.
? Post City, .