【发布时间】:2017-11-17 13:35:45
【问题描述】:
我和我的同事最近讨论了 EF 的良好做法。 所以我展示了我的一个。
他说有点糊涂。
我的实践在于以特定方式修改自动生成的类。 这是我的起始模型:
namespace PCServer.Data
{
using System;
using System.Collections.Generic;
public partial class Post: IEntity
{
public int Id { get; set; }
public string Title { get; set; }
public string Message { get; set; }
public DateTime Date { get; set; }
public virtual Post ParentPost { get; set; }
public virtual AspNetUser Author { get; set; }
}
}
我喜欢这样扩展:
public partial class Post
{
//This class "do" something, like adding a post or deleting a post
public static class Do
{
public static void AddPost(ref ApplicationDbContext context, string postMessage)
{
//Create a post
Post p = new Post();
p.Title = "This is an example!";
p.message = postMessage;
p.Date = DateTime.UtcNow;
//Adding to context
BaseService.Add(post, out context);
}
public static void DeletePost(ref ApplicationDbContext context, int postId)
{
PostRepository postRepo = new PostRepository(context);
postRepo.GetById(postId);
//Removing from context
BaseService.Remove(post, out context);
}
}
//This class "Get" something, like all posts
public static class Get
{
public static void GetPosts()
{
using(ApplicationDbContext context = new ApplicationDbContext())
{
PostRepository postRepo = new PostRepository(context);
return postRepo.GetAllPosts();
}
}
}
//This class "Set" something, like title of the post or the post itself maybe
public static class Set
{
public static void Title(ref ApplicationDbContext context, int postId, string title)
{
PostRepository postRepo = new PostRepository(context);
Post post = postRepo.GetById(postId);
post.Title = title;
BaseService.Update(post, out context);
}
public static void ChangePost(ref ApplicationDbContext context, int postId, Post post)
{
PostRepository postRepo = new PostRepository(context);
Post dbPost = postRepo.GetById(postId);
dbPost = post;
BaseService.Update(dbPost, out context);
}
}
}
所以,当我必须对实体做某事时,我可以(仅作为示例):
ApplicationDbContext c = new ApplicationDbContext();
Post.Do.AddPost(ref c,"Hi!");
IEnumerable<Post> posts = Post.Get.GetPosts();
Post.Set.Title(ref c,100,"Changing title!");
毕竟:
await BaseService.CommitAsync<Post>(c);
所以。 你怎么看?你会用吗?为什么?
谢谢你,很抱歉发了这么长的帖子。
【问题讨论】:
-
可以将其描述为 Active Record 模式。如果它适合您的需求,它是有效的。它不适用于复杂的企业系统。
-
这个问题是基于意见的,因此是题外话。我的意见?不。这属于服务。
标签: c# entity-framework coding-style forum