IdentityUser与其他表中的多对多在单独的上下文中

时间:2016-06-28 21:39:25

标签: entity-framework entity-framework-core

我在我的身份框架IdentityContextIdentityUser)和我的其他表之间创建连接表关系时遇到困难让我们称之为Entry。问题是,Entry处于一个完全独立的环境中,也是自己做的事情。

将这两者联系起来的正确方法是什么?我在哪里用流畅的api定义连接表?

现在,我收到以下错误。

The key {'ApplicationUserId'} contains properties in shadow state and is referenced by a relationship from 'ApplicationUser.ApplicationUserEntries' to 'ApplicationUserEntry.ApplicationUser'. Configure a non-shadow principal key for this relationship.

这些是我的表格的定义方式。

public class ApplicationUser : IdentityUser
    {
        ...

        public virtual List<ApplicationUserEntry> ApplicationUserEntries { get; set; }
    }


public class Entry
    {
        public int Id { get; set; }

        ...

        public virtual List<ApplicationUserEntry> ApplicationUserEntries { get; set; }
    }

连接表如​​下。

public class ApplicationUserEntry
    {
        public int ApplicationUserId { get; set; }
        public ApplicationUser ApplicationUser { get; set; }

        public int EntryId { get; set; }
        public Entry Entry { get; set; }
    }

对于IdentityContext我只有一些其他属性的通用设置

var users = modelBuilder.Entity<ApplicationUser>();
        users.Property(u => u.Name).IsRequired().HasMaxLength(65);
        users.Property(u => u.FirstName).HasMaxLength(32);
        users.Property(u => u.LastName).HasMaxLength(32);

在我的GoalsContext中,我有一些针对其他无关内容的常规设置,以及为ApplicationUserEntry定义的连接表

// Entry Configuration
var entries = modelBuilder.Entity<Entry>();
            entries.HasKey(e => e.Id);
            entries.HasAlternateKey(e => new { e.MilestoneId, e.CategoryId, e.MetricId });
            entries.Property(e => e.Value).IsRequired();
            entries.Property(e => e.Locked).IsRequired().HasDefaultValue(false);
            entries.ToTable("GoalsEntries");

// ApplicationUserEntry Join Table
modelBuilder.Entity<ApplicationUserEntry>()
            .ToTable("GoalsApplicationUserEntry")
            .HasKey(se => new { se.ApplicationUserId, se.EntryId });

modelBuilder.Entity<ApplicationUserEntry>()
            .HasOne(se => se.ApplicationUser)
            .WithMany(s => s.ApplicationUserEntries)
            .HasForeignKey(se => se.ApplicationUserId);

modelBuilder.Entity<ApplicationUserEntry>()
            .HasOne(se => se.Entry)
            .WithMany(e => e.ApplicationUserEntries)
            .HasForeignKey(se => se.EntryId);

现在我确定我显然错过了一些东西,但我无法弄清楚是什么。我从来没有尝试在两个不同的上下文中定义的两个表之间建立多对多的关系......甚至不确定这是否明智或不做。

我的最终目标是能够将所有者与Entry记录相关联,因此只能由所有者修改,我使用Identity Framework进行验证。

理想情况下,我更喜欢单向关系,因此我可以从Entry找到所有者,但我不打算通过查看Entry获取IdentityUser列表}

0 个答案:

没有答案
相关问题