【发布时间】:2014-11-07 04:04:33
【问题描述】:
我正在尝试掌握如何将 EF 用于即将进行的项目。
目前我有这个代码优先代码:
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public virtual List<Post> Posts { get; set; }
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public virtual Blog Blog { get; set; }
}
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
这创建了数据库和表,我已经能够添加博客/发布没有问题。但我对如何围绕 EF 代码优先方法进行结构感到困惑。
Blog 和Post 是否都应该引用BloggingContext,然后有自己的获取/添加/更新方法?
我是否应该创建单独的 BlogManager / PostManager 类来实际执行获取/添加/更新数据并简单地返回实体对象?
我是否应该创建从 Blog / Post 继承的包含 get / add / update 方法的单独类?
【问题讨论】:
-
我认为您应该什么都不做,因为您需要的所有内容都已在您的代码示例中到位。 DbContext 中的 DbSet 具有跟踪实体的机制。当您致电
dbContext.SaveChanges()时,所有跟踪的更改都将进入数据库 -
您通常希望创建
IBlogRepository和IPostRepository接口以及包装您的BloggingContext的相应实现。这样你就可以从你的业务逻辑类中抽象出 ORM 的实际实现和使用。
标签: c# entity-framework