Skip to content

Instantly share code, notes, and snippets.

Created June 8, 2014 01:53
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save anonymous/f98d1a4d6d760b87c58e to your computer and use it in GitHub Desktop.
namespace EF
{
public class Program
{
private static void Main()
{
var post = new Post
{
Slug = "hello-world",
Title = "Hello, World!",
Content = "this is my first post.",
Tags = new List<Tag>()
};
var tag = new Tag { Name = "introduction" };
post.Tags.Add(tag);
var db = new BlogDb();
using (var tagRepo = new Repository<Tag>(db))
using (var postRepo = new Repository<Post>(db))
{
tagRepo.Attach(tag); // comment this line and the code will work
postRepo.Add(post);
}
}
}
}
namespace EF.Domain
{
public class BlogDb : DbContext
{
public DbSet<Post> Posts { get; set; }
public DbSet<Tag> Tags { get; set; }
}
public class Repository<TEntity> : IDisposable where TEntity : class
{
private readonly DbContext _context;
public Repository(DbContext context)
{
_context = context;
}
public TEntity Add(TEntity entity)
{
_context.Set<TEntity>().Add(entity);
_context.SaveChanges();
return entity;
}
public void Attach(TEntity entity)
{
_context.Set<TEntity>().Attach(entity);
}
public void Dispose()
{
_context.Dispose();
}
}
}
namespace EF.Model
{
public class Post
{
[Key]
public string Slug { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
}
public class Tag
{
[Key]
public string Name { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment