How to add a foreign key to ApplicationUser between separate project in EF Core?

There is a Blazor WebAssembly Application with Asp.Net Core Hosting in .NET 5.0.0, which is separate to 3 different projects: WebApp.Client, WebApp.Server, WebApp.Shared.

And I’m using AspNetCore.Identity and IdentityServer4 to manage my application users.

But the class ApplicationUser : IdentityUser is in WebApp.Server project, while my model class Foo is in WebApp.Shared project. (The WebApp.Server project has the reference of WebApp.Shared project so that Foo can’t using WebApp.Server.Models.)

Can I add a foreign key to ApplicationUser class between separate project? Or can I move ApplicationUser to WebApp.Shared project?

Code

// WebApp.Server.Models.ApplicationUser

public class ApplicationUser : IdentityUser
{
    public virtual List<Foo> Foos { get; set; }
}
// WebApp.Shard.Models.Foo
public class Foo
{
    public int ApplicationUserId { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; } // CS0246 
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

A way without many dependencies is :

// WebApp.Shard.Models.Foo

using System.ComponentModel.DataAnnotations.Schema;

public class Foo<TUser>
{
    public int ApplicationUserId { get; set; }

    [ForeignKey(nameof(ApplicationUserId))]
    public virtual TUser ApplicationUser { get; set; }
}


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x