Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

Equivalent for .HasOptional in Entity Framework Core 1 (EF7)

Consider two classes.

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; }       
}

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);

What is equivalent in Entiity Framework Core 1?

Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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 will configure your relationship as optional (or N : 0..1 as requested).

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...