gpt4 book ai didi

c# - SQL Server CE 架构

转载 作者:太空宇宙 更新时间:2023-11-03 11:41:19 26 4
gpt4 key购买 nike

我必须构建一些小型的独立应用程序,这些应用程序可以复制到 USB 设备并从那里开箱即用。所以我想使用 WPF,它首先使用 EF 代码连接到 SQL Server CE 数据库。

我的问题是我应该使用什么架构。尽管这些应用程序是独立的,但我仍然希望将 UI 从域与数据分离,以实现清晰的层分离。但我也不想让它太复杂。

因此,我想要一个使用底层域层(具有域逻辑的域对象)和存储库(首先使用 EF 代码)的 UI 层 (WPF/MVVM)。

我的问题是:在这种情况下,我应该使用什么模式来使 EF 工作?是否有某个示例演示如何在这种情况下实现 CRUD 操作?例如,我是否应该创建一个上下文并将其保持打开状态?还是我应该实现工作单元模式并在需要时将对象附加到其他上下文?

或者您会以完全不同的方式进行吗?

多谢指教!

最佳答案

EF 上下文的打开时间应尽可能短。最好在 using 语句中使用它。

private static void ApplyItemUpdates(SalesOrderDetail originalItem,
SalesOrderDetail updatedItem)
{
using (AdventureWorksEntities context =
new AdventureWorksEntities())
{
context.SalesOrderDetails.Attach(updatedItem);
// Check if the ID is 0, if it is the item is new.
// In this case we need to chage the state to Added.
if (updatedItem.SalesOrderDetailID == 0)
{
// Because the ID is generated by the database we do not need to
// set updatedItem.SalesOrderDetailID.
context.ObjectStateManager.ChangeObjectState(updatedItem, System.Data.EntityState.Added);
}
else
{
// If the SalesOrderDetailID is not 0, then the item is not new
// and needs to be updated. Because we already added the
// updated object to the context we need to apply the original values.
// If we attached originalItem to the context
// we would need to apply the current values:
// context.ApplyCurrentValues("SalesOrderDetails", updatedItem);
// Applying current or original values, changes the state
// of the attached object to Modified.
context.ApplyOriginalValues("SalesOrderDetails", originalItem);
}
context.SaveChanges();
}
}

有一个名为 Attach 的方法,它将实体附加到上下文:

private static void AttachRelatedObjects(
ObjectContext currentContext,
SalesOrderHeader detachedOrder,
List<SalesOrderDetail> detachedItems)
{
// Attach the root detachedOrder object to the supplied context.
currentContext.Attach(detachedOrder);

// Attach each detachedItem to the context, and define each relationship
// by attaching the attached SalesOrderDetail object to the EntityCollection on
// the SalesOrderDetail navigation property of the now attached detachedOrder.
foreach (SalesOrderDetail item in detachedItems)
{
currentContext.Attach(item);
detachedOrder.SalesOrderDetails.Attach(item);
}
}

http://msdn.microsoft.com/en-us/library/bb896271.aspx

关于c# - SQL Server CE 架构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4713967/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com