结合使用实体框架和WPF数据绑定的最佳实践 [英] Best practices for using the Entity Framework with WPF DataBinding

查看:82
本文介绍了结合使用实体框架和WPF数据绑定的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建我的第一个真正的WPF应用程序(即第一个打算供我以外的人使用的应用程序),而我仍在全力以赴地寻求最佳的WPF处理方式。这是一个使用还很新的Entity Framework的相当简单的数据访问应用程序,但是我无法在线找到很多指南,以获取将这两种技术(WPF和EF)结合使用的最佳方法。所以我想我会抛弃我的方式,看看是否有人有更好的建议。

I'm in the process of building my first real WPF application (i.e., the first intended to be used by someone besides me), and I'm still wrapping my head around the best way to do things in WPF. It's a fairly simple data access application using the still-fairly-new Entity Framework, but I haven't been able to find a lot of guidance online for the best way to use these two technologies (WPF and EF) together. So I thought I'd toss out how I'm approaching it, and see if anyone has any better suggestions.


  • 我我正在将实体框架与SQL Server 2008一起使用。EF使我感到震惊,因为两者都比它需要的复杂得多,并且还不成熟,但是Linq-to-SQL显然已经死了,所以我不妨使用那种MS似乎专注于此。

  • I'm using the Entity Framework with SQL Server 2008. The EF strikes me as both much more complicated than it needs to be, and not yet mature, but Linq-to-SQL is apparently dead, so I might as well use the technology that MS seems to be focusing on.

这是一个简单的应用程序,因此(尚未)我认为适合在其周围构建一个单独的数据层。当我想获取数据时,我使用相当简单的Linq-to-Entity查询,通常直接从我的代码后面获取,例如:

This is a simple application, so I haven't (yet) seen fit to build a separate data layer around it. When I want to get at data, I use fairly simple Linq-to-Entity queries, usually straight from my code-behind, e.g.:

var families = from family in entities.Family.Include("Person")
           orderby family.PrimaryLastName, family.Tag
           select family;


  • Linq-to-Entity查询返回IOrderedQueryable结果,该结果不会自动反映更改在基础数据中,例如,如果我通过代码向实体数据模型添加新记录,则该新记录的存在不会自动反映在引用Linq查询的各种控件中。因此,我将这些查询的结果放入ObservableCollection中,以捕获基础数据更改:

  • Linq-to-Entity queries return an IOrderedQueryable result, which doesn't automatically reflect changes in the underlying data, e.g., if I add a new record via code to the entity data model, the existence of this new record is not automatically reflected in the various controls referencing the Linq query. Consequently, I'm throwing the results of these queries into an ObservableCollection, to capture underlying data changes:

    familyOC = new ObservableCollection<Family>(families.ToList());
    


  • 然后我将ObservableCollection映射到CollectionViewSource,以便进行过滤,排序,

  • I then map the ObservableCollection to a CollectionViewSource, so that I can get filtering, sorting, etc., without having to return to the database.

    familyCVS.Source = familyOC;
    familyCVS.View.Filter = new Predicate<object>(ApplyFamilyFilter);
    familyCVS.View.SortDescriptions.Add(new System.ComponentModel.SortDescription("PrimaryLastName", System.ComponentModel.ListSortDirection.Ascending));
    familyCVS.View.SortDescriptions.Add(new System.ComponentModel.SortDescription("Tag", System.ComponentModel.ListSortDirection.Ascending));
    


  • 然后我将各种控件和不该绑定的控件绑定到该CollectionViewSource:

  • I then bind the various controls and what-not to that CollectionViewSource:

    <ListBox DockPanel.Dock="Bottom" Margin="5,5,5,5" 
        Name="familyList" 
        ItemsSource="{Binding Source={StaticResource familyCVS}, Path=., Mode=TwoWay}" 
        IsSynchronizedWithCurrentItem="True" 
        ItemTemplate="{StaticResource familyTemplate}" 
        SelectionChanged="familyList_SelectionChanged" />
    


  • 当我需要添加或删除记录/对象时,我会手动从实体数据模型以及ObservableCollection:

  • When I need to add or delete records/objects, I manually do so from both the entity data model, and the ObservableCollection:

    private void DeletePerson(Person person)
    {
        entities.DeleteObject(person);
        entities.SaveChanges();
        personOC.Remove(person);
    }
    


  • 我通常使用StackPanel和DockPanel控件定位元素。有时我会使用网格,但似乎很难维护:如果要在网格顶部添加新行,则必须触摸网格直接托管的每个控件,以使其使用新行。 U (微软似乎从未真正获得过DRY概念。)

  • I'm generally using StackPanel and DockPanel controls to position elements. Sometimes I'll use a Grid, but it seems hard to maintain: if you want to add a new row to the top of your grid, you have to touch every control directly hosted by the grid to tell it to use a new line. Uggh. (Microsoft has never really seemed to get the DRY concept.)

    我几乎从不使用VS WPF设计器来添加,修改或定位控件。 VS附带的WPF设计器在某种程度上模糊地帮助您查看表单的外观,但是即便如此,还是不​​行,特别是如果您使用的数据模板未绑定到可从以下网站获得的数据时设计时间。如果我需要编辑XAML,则可以像男人一样手动处理。

    I almost never use the VS WPF designer to add, modify or position controls. The WPF designer that comes with VS is sort of vaguely helpful to see what your form is going to look like, but even then, well, not really, especially if you're using data templates that aren't binding to data that's available at design time. If I need to edit my XAML, I take it like a man and do it manually.

    我的大部分实际代码都使用C#而不是XAML。正如我提到的其他地方,完全除了我还不习惯于思考这一事实之外,XAML令我感到它是一种笨拙,丑陋的语言,而且它恰巧也缺乏对设计师和智能感知的支持,因此无法调试。 U因此,每当我能清楚地看到如何在C#代码中执行某些操作时,却看不到如何在XAML中执行该操作,我都会在C#中这样做,而无需道歉。关于如何避免在WPF页面中几乎不使用代码隐藏(例如,用于事件处理)的良好实践,已有很多文章,但至少到目前为止,这对我来说毫无意义。当我可以使用像C#这样具有世界一流的编辑器,近乎完美的好而干净的语言时,为什么要用令人讨厌的语法,丑陋的笨拙语言,令人惊讶的糟糕编辑器以及几乎没有类型安全性来做某事?智能感知和无与伦比的类型安全性?

    Most of my real code is in C# rather than XAML. As I've mentioned elsewhere, entirely aside from the fact that I'm not yet used to "thinking" in it, XAML strikes me as a clunky, ugly language, that also happens to come with poor designer and intellisense support, and that can't be debugged. Uggh. Consequently, whenever I can see clearly how to do something in C# code-behind that I can't easily see how to do in XAML, I do it in C#, with no apologies. There's been plenty written about how it's a good practice to almost never use code-behind in WPF page (say, for event-handling), but so far at least, that makes no sense to me whatsoever. Why should I do something in an ugly, clunky language with god-awful syntax, an astonishingly bad editor, and virtually no type safety, when I can use a nice, clean language like C# that has a world-class editor, near-perfect intellisense, and unparalleled type safety?

    这就是我的意思。有什么建议么?我是否错过了其中的大部分内容?我真的应该考虑做其他事情吗?

    So that's where I'm at. Any suggestions? Am I missing any big parts of this? Anything that I should really think about doing differently?

    推荐答案

    您需要实现一个存储库模式,以将WPF关注点与EF分开

    You need to implement a repository pattern to seperate WPF concerns from EF

    然后您可以使用泛型来降低EF到CollectionViewSource处理的复杂性

    Then you can use generics to reduce the complexity of the EF to CollectionViewSource handling

    设计良好的存储库应减少代码级别并允许替换任何ORM(进行体面测试所需)

    A well designed repository should reduce code levels and enable any ORM to be substituted (required for decent testing)

    此处有一些想法

    http:// blog.nicktown.info/2008/12/10/using-a-collectionviewsource-to-display-a-sorted-entitycollection.aspx

    这篇关于结合使用实体框架和WPF数据绑定的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆