简体   繁体   English

在实体框架中定义一对一关系

[英]Defining one to zero relationship in Entity Framework

I have a relationship that I'm not sure how to define, I'm quite new to SQL so I might have it wrong. 我有一个不确定的关系,我对SQL还是很陌生,所以我可能会记错了。

I have an Account which looks like this: 我有一个看起来像这样的Account

public class Account
{
    public int Id { get; set; }
    public string Username { get; set; }
    public LiveCurrencyInfo CurrencyInfo { get; set; }
}

And LiveCurrencyInfo: 和LiveCurrencyInfo:

public class LiveCurrencyInfo
{
    public int Id { get; set; }
    public decimal USD { get; set; }
}

Account needs to have a link to a single LiveCurrencyInfo entity. Account需要具有指向单个LiveCurrencyInfo实体的链接。

LiveCurrencyInfo exists as a completely separate entity which doesn't depend on anything else - as it's defined. LiveCurrencyInfo作为一个完全独立的实体存在,它不依赖于其他任何东西-正如它定义的那样。

Is this a 1..0 relationship? 这是1..0关系吗?

I tried defining it like this but the syntax is wrong: 我试图这样定义它,但是语法错误:

protected override void OnModelCreating(DbModelBuilder mb)
{
    mb.Entity<Account>()
        .HasRequired(l => l.CurrencyInfo)
        .Map(m =>                        //Can't call .Map here
        {
            m.MapLeftKey("AccountId");
            m.MapRightKey("LiveCurrencyInfoId");
            m.ToTable("UserAccountLiveCurrencyMapping");
        });
}

Edit 编辑

I think the tables would look like the following: 我认为这些表格如下所示:

Accounts         LiveCurrencyInfo         UserAccountLiveCurrencyMapping

Id | Username    Id | USD                 AccountId | LiveCurrencyInfoId
---+---------    ---+------               ----------+-------------------
20 | User_1      39 | 1.0                 20        | 39

Is this a 1..0 relationship? 这是1..0关系吗?

First you need to define the relationship ends (from -> to). 首先,您需要定义关系的结尾(从->到)。 But no, there is no such relationship at all. 但是不,根本没有这种关系。

According to your explanation, the relationship from LiveCurrencyInfo to Account is 1 -> 0..1 . 根据您的解释,从LiveCurrencyInfoAccount的关系是1 -> 0..1 Hence by EF terms LiveCurrencyInfo is the principal end and Account is the dependent end. 因此,按EF术语来说, LiveCurrencyInfo主要方面,Account从属方面 Since as I understand both entities should have independent PKs, then Account would need FK column referencing LiveCurrencyInfo PK. 由于据我所知,两个实体都应具有独立的PK,因此Account将需要FK列引用LiveCurrencyInfo PK。

The fluent setup is as follows (in order to make Map and other relationship fluent APIs available, you need first to complete the relationship ends definition started by HasXyz with the appropriate WithXyz ): 流畅的设置如下(为了使Map和其他关系流畅的API可用,您需要首先使用适当的WithXyz完成由HasXyz开始的关系终点定义):

mb.Entity<Account>()
    .HasRequired(e => e.CurrencyInfo)
    .WithOptional()
    .Map(m => m.MapKey("LiveCurrencyInfoId"));

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

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