简体   繁体   English

实体框架 - 将 Combobox 绑定到规范化表字段

[英]Entity Framework - Bind Combobox to Normalised Table Field

I am currently trying to bind an entity to a form however I want to have DataConfidenceLevel (see below) bound to a combobox with ConfidenceDescription as the display member.我目前正在尝试将实体绑定到表单,但是我希望将 DataConfidenceLevel(见下文)绑定到 combobox,并以 ConfidenceDescription 作为显示成员。 What is the correct way to populate the combobox?填充 combobox 的正确方法是什么?

(I am currently using WPF but a Winforms answer is acceptable) (我目前正在使用 WPF 但可以接受 Winforms 答案)

Thanks谢谢

Entity Designer http://img19.imageshack.us/img19/374/entity.png实体设计器 http://img19.imageshack.us/img19/374/entity.png

You want to bind a collection to a control and have a releated entity - namely navigation property DataConfidenceLevel of type DataConfidenceLevel - as the display member?您想将集合绑定到控件并具有相关实体 - 即 DataConfidenceLevel 类型的导航属性 DataConfidenceLevel - 作为显示成员?

That is usually achieved really simple by overriding ToString(),这通常通过重写 ToString() 来实现,非常简单,

public partial class DataConfidenceLevel
{
   public override String ToString()
   {
      return this.ConfidenceDescription;
   }
}

and than setting DisplayMember to the DataConfidenceLevel property of the entity you want to bind.而不是将 DisplayMember 设置为要绑定的实体的 DataConfidenceLevel 属性。

The answer was simpler than I was expecting.答案比我预期的要简单。

    comboBox.DataBindings.Add(new Binding("SelectedItem", this.dataBindingSource, "DataConfidenceLevel", true));
    comboBox.DataSource = db.DataConfidenceLevel;
    comboBox.DisplayMember = "ConfidenceDescription";
    comboBox.ValueMember = "ConfidenceLevelID";

I wrote two blog entries about one approach to handling this situation - it applies to ASP.net, but it might help you out.我写了两篇关于处理这种情况的方法的博客文章——它适用于 ASP.net,但它可能会对你有所帮助。

Here are the posts, the first one is more of an introduction to the problem, the second entry shows how to pin it all together.这是帖子, 第一个更多的是对问题的介绍, 第二个条目显示了如何将它们固定在一起。

I'm not sure whether this qualifies as "the correct way" but it's certainly an approach:) I'd be happy to hear back if this helps you out!我不确定这是否符合“正确方法”的条件,但这肯定是一种方法:)如果这对您有帮助,我很高兴收到回复!

Edit: After reading danbruc's answer, you can certainly override ToString on the Navigation property as he has suggested (for read only), but that's only a partial answer.编辑:阅读 danbruc 的答案后,您当然可以按照他的建议覆盖 Navigation 属性上的 ToString (只读),但这只是部分答案。

This won't work unless your LINQ query contains the "Include" statement, eg除非您的 LINQ 查询包含“包含”语句,否则这将不起作用,例如

var listOfThings = (from t in db.Thingy
                    .Include("DataConfidenceLevel")
                    select t).ToList();

Omitting the.Include() means that nothing will get bound to the column.省略 .Include() 意味着没有任何内容会绑定到该列。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM