配置许多实体框架代码优先和流利的API一比一的关系 [英] Configuring many One-To-One relationships with Entity Framework Code First and Fluent API

查看:187
本文介绍了配置许多实体框架代码优先和流利的API一比一的关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可怕的数据库模型(在MySQL中,虽然我不认为事情),别人设计的,所以我坚持了下来,但仍要与实体框架使用它:

I have a horrible database model (in MySQL though I don't think that matters) that someone else designed so I'm stuck with it, but want to use with Entity Framework with it anyway:

项目

ASSET_ID*   ASSET_NAME  FIELDS_ID
1          Cat         1
2          Dog         2
3          Fish        3

ItemFields

ID*    CUSTOMFIELD1ID    CUSTOMFIELD2ID    CUSTOMFIELD3ID
1     1001              1002              1003
2     1004              1005              1006
3     1007              1008              1009

字段

ID*    STRINGVAL
1001   Meow Mix
1002   House
1003   5lbs
1004   Kibble
1005   Yard
1006   30lbs
1007   Fish Food
1008   Tank
1009   0.5 ounces

*指示表的PK


*indicates table's PK


最后,我想配置的关系,这样我就可以得到这样的自定义数据:

Ultimately, I'm trying to configure the relationships so I can get custom data like this:

Item item = GetItem(1);
item.Food.ToString(); // Output: meow mix
item.Place.ToString(); // Output: house
item.Weight.ToString(); // Output: 5 lbs 



...等。但老实说,我想在这一点上解决这个:

...etc. but honestly I'd settle for this at this point:

Item item = GetItem(1);
Item.ItemFields.CustomField3.Value // Output: 5 lbs
Item item = GetItem(2);
Item.ItemFields.CustomField2.Value // Output: Yard
Item item = GetItem(3);
Item.ItemFields.CustomField1.Value // Output: Fish Food





到目前为止,我已经得到了这一点:

So far I've got this:

一比一:项目 - ItemFields

modelBuilder.Entity<Item>()
    .HasRequired(x => x.ItemFields)
    .WithRequiredPrincipal(y => y.Item);



但ItemFields.CustomField1ID到Field.ID有关映射是什么?

But what about mapping ItemFields.CustomField1ID to Field.ID?

它甚至有可能来配置这样的使用EF代码首先有关系吗?我很困惑这是否是一个一对一或一对多......我认为它实际上是是众多一到那些(如果是有道理的)。

Is it even possible to configure a relationship like this using EF code first? I'm pretty confused about whether or not this is a one-to-one or a one-to-many... I think what it actually is is many one-to-ones (if that makes sense).

有什么建议?

推荐答案

我可能已经想通了这一点。我编辑我的ItemFields类是这样的:

I may have figured this out. I edited my ItemFields class to look like this:

public class ItemFields
{
    public int Id { get; set; }
    public int CUSTOMFIELD1ID { get; set; }
    public virtual Field CustomField1 { get; set; }

和则配置了这些关系:

modelBuilder.Entity<Item>()
    .HasRequired(x => x.CustomField1)
    .WithMany()
    .HasForeignKey(x => x.CUSTOMFIELD01_ID);
modelBuilder.Entity<Item>()
    .HasRequired(x => x.CustomField2)
    .WithMany()
    .HasForeignKey(x => x.CUSTOMFIELD02_ID);

和它似乎已经奏效,但说实话,我不完全理解为什么。我还是最想要将它们映射到更加人性化的类。

And it seems to have worked, though to be honest I don't fully understand why. I'd still ideally like to map them to more user-friendly classes.

这篇关于配置许多实体框架代码优先和流利的API一比一的关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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