/gist:f98d1a4d6d760b87c58e Secret
Created
June 8, 2014 01:53
Star
You must be signed in to star a gist
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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