简体   繁体   中英

Relationship in Fluent API in Entity Framework Core

I need to create a relationship between two tables that share a common column of type string - how can I do that?

This is what I did. Does this work?

You need to specify the foreign key (preferably always) and the principal key (if it is different to the primary key). In order to use a principal key other than Primary Key, you need to create a UNIQUE Constraint. In EF you can do this by specifying HasIndex and IsUnique, otherwise you will get an error because the selected principal key is not a unique column.

See this example:

//HaweyTajer is the principal table
modelbuilder.Entity<HaweyTajer>(entity => 
{
   //Mark the primary key
   entity.HasKey(x => x.Id);

   //Build the relation (Consider adding OnDelete())
   entity.HasMany(x => x.Certivicates)
         .WithOne(x => x.HaweyTaker)
         .HasPrincipalKey(x => x.AZbaraNum)
         .HasForeignKey(x => x.AZbaraNum);

   //Build the index on the column inside the principal table
   entity.HasIndex(x => x.AZbaraNum)
         .IsUnique();
   
});

You might as well change the column type to not nvarchar(250) not null or add a filter to the index with HasFilter().

Reference: https://learn.microsoft.com/en-us/ef/ef6/modeling/code-first/fluent/relationships

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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