简体   繁体   English

使用Entity Framework Core防止一对一映射

[英]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. 我正在重构ASP.NET Core应用程序中的一些EF Core代码,并且为了使某些应用程序特定的代码与某些Framework代码(身份)脱钩,我想手动管理关系而不是使用EF核心创建一对一映射。

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. 我实质上希望从一个类到另一个类进行引用,这是一对一的映射,但是要使其引用,以使EF Core不会尝试自动建立这种关系。

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. ApplicationUser类用于Identity,另一个表是特定于应用程序的。

Is there a way with EF Core to tell it not to create a one-to-one mapping between these classes? EF Core是否有办法告诉它不要在这些类之间创建一对一映射?

Thanks 谢谢

You can use the Ignore() function on your modelBuilder inside the overriden method OnModelCreating() of your DbContext like this: 您可以使用Ignore()函数在你的modelBuilder的覆盖方法中OnModelCreating()你的DbContext是这样的:

    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 
   }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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