简体   繁体   中英

Prevent one-to-one mapping with Entity Framework Core

I'm refactoring some EF Core code in an ASP.NET Core application, and in an effort to decouple some of the application specific code from some of the Framework code (Identity) I'd like to manually manage a relationship instead of having EF Core create a one-to-one mapping.

I would like to essentially have a reference from one class to another class, which is a one-to-one mapping, but make it so that EF Core doesn't attempt to build this relationship up automatically.

So I have:

  public class ApplicationUser : IdentityUser
  {
     public Author Author { get; set; }
  }

And:

public class Author
{
    public long Id { get; set; }
    public string ApplicationUserId { get; set; }
    public ApplicationUser ApplicationUser { get; set; }
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
    public string Biography { get; set; }
    public virtual ICollection<BlogPost> BlogPosts { get; set; }
  }

And then in my context, both of these become tables. The ApplicationUser class is for Identity, the other table is more application specific.

Is there a way with EF Core to tell it not to create a one-to-one mapping between these classes?

Thanks

You can use the Ignore() function on your modelBuilder inside the overriden method OnModelCreating() of your DbContext like this:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<ApplicationUser >().Ignore(u => u.Author);
        modelBuilder.Entity<Author>().Ignore(a => a.ApplicationUser);

        //rest of the code 
   }

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