【问题标题】:Prevent one-to-one mapping with Entity Framework Core防止与 Entity Framework Core 的一对一映射
【发布时间】:2017-04-15 16:24:37
【问题描述】:

我正在重构 ASP.NET Core 应用程序中的一些 EF Core 代码,并且为了将一些特定于应用程序的代码与一些框架代码(身份)分离,我想改为手动管理关系让 EF Core 创建一对一映射。

我希望本质上具有从一个类到另一个类的引用,这是一对一的映射,但要做到这一点,以便 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 类用于标识,另一个表更特定于应用程序。

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

谢谢

【问题讨论】:

    标签: c# asp.net entity-framework entity-framework-core


    【解决方案1】:

    您可以在 modelBuilderOnModelCreating() 的覆盖方法 OnModelCreating() 上使用 Ignore() 函数,如下所示:

        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 
       }
    

    【讨论】:

    • 我可以在属性上使用 [NotMapped] 属性。但这看起来也会奏效。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 2018-08-30
    • 2013-06-04
    • 2017-02-17
    • 2018-03-08
    相关资源
    最近更新 更多