EF Core - create relation between two models without a foreign key constaint

Viewed 86

I'm working on a microservice system where I replicate Users and Tokens across multiple services.

Sometimes, Token is received before User that it belongs to and I get an error:

MessageText: insert or update on table "Tokens" violates foreign key constraint "FK_Tokens_User_UserId"
Detail: Key (UserId)=(12) is not present in table "User".

Is there a way in EFCore to have relations with navigational properties, but without the constraint - so I can add Token with a not-yet-existing Id as foreign key, that'll eventually be consistent?

Here's the models:

Token:

public class Token
{
    public long Id { get; set; }

    public long? UserId { get; set; }
    
    public virtual User User { get; set; }
}

User:

public class User
{
    public long Id { get; set; }

    public virtual ICollection<Token> Tokens { get; set; }
}

Here's the portion of migration.designer.cs generating foreign key:

modelBuilder.Entity("Vehicloo.NoticeboardService.Database.Models.Token", b =>
{
    b.HasOne("Vehicloo.NoticeboardService.Database.Models.User", "User")
        .WithMany("Tokens")
        .HasForeignKey("UserId");

    b.Navigation("User");
});
1 Answers

Just remove line:

public virtual ICollection<Token> Tokens { get; set; }

from User and this line:

public virtual User User { get; set; }

from Token. This tells EF not create any foreign key for the User-Token. Consequently, you will have the UserId column in the Token table without any constraint.

For queries, you can join two table manually.

Related