Search code examples
c#asp.netentity-framework-coreblazorblazor-webassembly

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 
}

Solution

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