繁体   English   中英

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

[英]Prevent one-to-one mapping with Entity Framework Core

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

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

所以我有:

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

和:

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

然后在我的上下文中,这两个都成为表。 ApplicationUser类用于Identity,另一个表是特定于应用程序的。

EF Core是否有办法告诉它不要在这些类之间创建一对一映射?

谢谢

您可以使用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