简体   繁体   English

MVVM绑定到实体框架中的外键属性

[英]MVVM Binding to Foreign Key Property in Entity Framework

I'm getting started with Entity Framework and need some help understanding the functionality between two Tables. 我现在开始使用实体框架,需要一些帮助来理解两个表之间的功能。 To start with I have PhoneRecords and PhoneModels . 首先,我有PhoneRecordsPhoneModels Each PhoneRecord has a property called PhoneModelId that relates to one of the PhoneModels . 每个PhoneRecord都有一个名为PhoneModelId的属性,该属性与PhoneModels之一PhoneModels In MySQL these properties are setup as a foreign key relationship. 在MySQL中,这些属性被设置为外键关系。

Now I've loaded a sample of PhoneRecords into a DataGrid . 现在,我已经将PhoneRecords的示例加载到DataGrid I have a TextBox that I want to reflect the model on the PhoneRecord . 我有一个TextBox ,我想在PhoneRecord上反映模型。 At present my TextBox looks like so: 目前,我的TextBox如下所示:

<TextBox Grid.Row="1" Grid.Column="1" Text="{Binding SelectedRecord.PhoneModelId}"/>

and, unsurprisingly, the Id is displayed instead of the Name of the PhoneModel . 毫不奇怪,将显示Id而不是PhoneModelName Usually without EntityFramework I would just have a property on the PhoneRecord itself called PhoneModelName or something similar which I would get using a JOIN when writing out my SELECT commands.. 通常没有EntityFramework,我只会在PhoneRecord本身上拥有一个名为PhoneModelName的属性,或者在写出SELECT命令时使用JOIN获得的类似属性。

It seems to me that that method is old fashioned, and that Entity Framework is a powerful tool for getting around writing long CRUD operations. 在我看来,该方法是过时的,而Entity Framework是一种用于编写较长的CRUD操作的强大工具。 However, I am stuck in seeing how I am able to bind in MVVM to the PhoneModel name rather than using the PhoneModelId property on the PhoneRecord . 但是,我被困在如何将MVVM中绑定到PhoneModel名称上,而不是使用PhoneModelId上的PhoneRecord属性上。

Try something like: 尝试类似:

"{Binding SelectedRecord.PhoneModel.Name}"

I'm not sure which version of EF you're using or which flavour (code-first, DB first, code-first with existing database, etc.)... but... 我不确定您使用的是哪个版本的EF或哪种风格(代码优先,数据库优先,现有数据库的代码优先等)...但是...

In EF if you have an object that has a foreign key relationship it will attach that object to it's parent or child. 在EF中,如果您有一个具有外键关系的对象,它将将该对象附加到其父项或子项。 So each PhoneRecord will have a PhoneModel object attached to it, and vice versa. 因此,每个PhoneRecord都将附加一个PhoneModel对象,反之亦然。 If you're using code first, you'll have to code this relationship, if you're using DB first it should already exist int the model (EDMX) and you should be able to navigate to a PhoneModel from a PhoneRecord and back again. 如果您首先使用代码,则必须编写此关系的代码,如果您首先使用数据库,则它应该已经存在于模型(EDMX)中,并且您应该能够从PhoneRecord导航到PhoneModel并再次返回。

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

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