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

早过忘川 提交于 2019-11-29 09:02:59
octavioccl

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.

Sina Lotfi

In EF Core you can using two ways for relating two tables:

  • Inside OnModelCreating:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);            
    
        modelBuilder.Entity<File>()
                    .HasOne(c => c.Message)
                    .WithOne()
                    .HasForeignKey(c => c.MessageId)                           
    }
    
  • Create new class FileConfiguration and calling it inside OnModelCreating:

    public class FileConfiguration : IEntityTypeConfiguration<File>
    {
        public void Configure(EntityTypeBuilder<File> builder)
        {           
            builder.ToTable("File");            
    
            // Id
            builder.HasKey(c => c.Id);
            builder.Property(c => c.Id)
                   .ValueGeneratedOnAdd();
    
            // Message
            builder.HasOne(c => c.Message)
                   .WithOne(c => c.File)
                   .HasForeignKey<Message>(c => c.MessageId)
                   .OnDelete(DeleteBehavior.Restrict);
        }
    }
    

    and inside OnModelCreating put below codes:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    
        modelBuilder.ApplyConfiguration(new FileConfiguration());                                       
    }
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!