等效于 Entity Framework Core 1 (EF7) 中的 .HasOptional [英] Equivalent for .HasOptional in Entity Framework Core 1 (EF7)

查看:22
本文介绍了等效于 Entity Framework Core 1 (EF7) 中的 .HasOptional的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑两个类.

public class File
{
    [Key]
    public string Id { get; set; }

    public string Message_Id { get; set; }

    internal Message Message { get; set; }
}

public class Message 
{
    [Key]
    public string Id { get; set; }       
}

在 EF6 中,对于 N : 1..0 关系,有这个流畅的 API.

In EF6, for N : 1..0 relation there was this fluent API.

modelBuilder.Entity<File>()
            .HasOptional(e => e.Message ).WithMany().HasForeignKey(e => e.Message_Id);

Entity Framework Core 1 中的等效项是什么?

What is equivalent in Entiity Framework Core 1?

谢谢

推荐答案

您不会在 EF 7 中找到等效的方法.按照惯例,其 CLR 类型可以包含 null 的属性将被配置为可选的.那么决定关系是否可选的是 FK 属性是否 nullable 或不分别.

You will not find an equivalent method in EF 7. By convention, a property whose CLR type can contain null will be configured as optional. So what decide if the relationship is optional or not is if the FK property is nullable or not respectively.

总而言之,由于您的Message_Id FK 属性是string,它已经接受null 值,因此如果您使用以下Fluent Api配置:

In summary, due to your Message_Id FK property is string, it already accepts null value, so if you use the following Fluent Api configuration:

modelBuilder.Entity<File>()
            .HasOne(s => s.Message)
            .WithMany()
            .HasForeignKey(e => e.Message_Id)

EF 会将您的关系配置为可选(或 N : 0..1 根据要求).

EF will configure your relationship as optional (or N : 0..1 as requested).

如果您的 FK 属性是像 int 这样的值类型,您应该将其声明为可空 (int?).

In case of your FK property is value type like int, you should declare it as nullable (int?).

我还注意到现在你有一个带有 internal 访问修饰符的导航属性.您应该始终将实体属性声明为 public.

Also I noticed now you have a navigation property with internal access modifier. You should always declare your entity properties as public.

这篇关于等效于 Entity Framework Core 1 (EF7) 中的 .HasOptional的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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