Wpf 如何使用实体框架组织项目中的层?
我在组织我的项目时左右为难。我正在创建一个发送新闻稿的应用程序。在我的解决方案中,我将其分为三个项目:Wpf 如何使用实体框架组织项目中的层?,wpf,entity-framework,service-layer,Wpf,Entity Framework,Service Layer,我在组织我的项目时左右为难。我正在创建一个发送新闻稿的应用程序。在我的解决方案中,我将其分为三个项目:Newsletter.UI(WPF)、Newsletter.DAL和Newsletter.Services。在Newsletter.DAL中,有一些类表示EF在其他文件中增强生成的实体(它们是部分类)-覆盖ToString()。在Newsletter.UI中有一个cource WPF项目的演示。我的问题始于时事通讯.Services 现在我创建了MailingListService.cs: us
Newsletter.UI
(WPF)、Newsletter.DAL
和Newsletter.Services
。在Newsletter.DAL
中,有一些类表示EF在其他文件中增强生成的实体(它们是部分类)-覆盖ToString()
。在Newsletter.UI
中有一个cource WPF项目的演示。我的问题始于时事通讯.Services
现在我创建了MailingListService.cs
:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newsletter.DAL;
namespace Newsletter.Services
{
public class MailingListService
{
private NewsletterEntities _context;
public MailingListService()
{
_context = new NewsletterEntities();
}
public List<string> GetAllMailingListsNames()
{
var query = from m in _context.MailingLists select new { m.Name };
List<string> names = new List<string>();
foreach (var m in query)
names.Add(m.Name);
return names;
}
public List<MailingList> GetAllMailingLists()
{
var query = from m in _context.MailingLists select m;
return query.ToList();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newsletter.DAL;
using System.Data.Entity;
namespace Newsletter.Services
{
public class MessageService
{
private NewsletterEntities _context;
public MessageService()
{
_context = new NewsletterEntities();
}
public List<Message> GetAllMessages()
{
return (from m in _context.Messages select m).ToList();
}
public static Message GetMessageByID(int id)
{
using (NewsletterEntities context = new NewsletterEntities())
{
Message message = (from m in context.Messages where m.MessageID == id select m).FirstOrDefault();
return message;
}
}
}
}
RecipientService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newsletter.DAL;
namespace Newsletter.Services
{
public class RecipientService
{
private NewsletterEntities _context;
public RecipientService()
{
_context = new NewsletterEntities();
}
public void addRecipient(Recipient newRecipient)
{
_context.Recipients.AddObject(newRecipient);
}
}
}
然而,这会产生问题。当我打开创建收件人的窗口时,我会创建一个MailingListService
实例来加载邮件列表的名称。然后,当我尝试创建一个新的收件人
时,我会创建一个RecipientService
实例并尝试添加一个收件人。我得到一个错误,我不能在不同的地方使用上下文
如何解决这个问题?我的方法不好吗?应该是什么(服务中应该是什么)?我不想在将来犯这样的错误。我现在不想学习MVVM方法,我需要或多或少地按照我现在的方式来学习。有几种方法是可能的:
AddRecipient
方法中,首先分离收件人(在检查是否已附加收件人后),并将其附加到当前上下文。但是:现在工作单元在两个上下文实例之间被分割,您需要一个TransactionScope
来保持它的事务性邮件服务
public Recipient AddRecipient(时事通讯实体上下文、字符串名称、字符串电子邮件)
)。(通过传递名称等。该服务负责创建新的收件人
对象或返回现有对象(如果它们已经存在)只有一些想法:)。有几种可能的方法:
AddRecipient
方法中,首先分离收件人(在检查其是否已附加后),并将其附加到当前上下文。但是:现在,工作单元在两个上下文实例之间分开,您需要一个TransactionScope
来保持其事务性邮件服务
公共收件人AddRecipient(上下文、字符串名称、字符串电子邮件)
)。(通过传递名称等。该服务负责创建新的收件人
对象或返回现有对象(如果它们已经存在)有几点想法:)。您看到的确切错误消息是什么?错误发生在哪一行?您看到的确切错误消息是什么?错误发生在哪一行?