Entity Framework 6.1.3 Foreign Key on non primary key field

穿精又带淫゛_ 提交于 2019-12-08 05:58:09

问题


I have the following 2 classes:

public class UserMembership: Entity
{
    public Guid Id { get; set; }
    public Guid UserGroupId { get; set; }
    public string LoginId { get; set; }
    public Guid SiteId { get; set; }

    public virtual Site Site { get; set; }
    public virtual SecurityUser SecurityUser { get; set; }
}

and

public class SecurityUser: Entity
{
    ICollection<UserMembership> _userMemberships = new Collection<UserMembership>();

    public Guid Id { get; set; }
    public string LoginId { get; set; }
    public string DisplayName { get; set; }
    public DateTimeOffset? LastLogOn { get; set; }
    public bool IsActive { get; set; }
    public bool IsServiceAccount { get; set; }
    public bool IsUserAccount { get; set; }

    public virtual ICollection<UserMembership> UserMemberships 
    {
        get { return _userMemberships; }
        set { _userMemberships = value; }
    }
}

And want to join UserMembership and SecurityUser using the LoginId fields NOT the primary key. Is this possible using the Fluent API and not attributes?

Here are the mapping classes:

public class SecurityUserMap : EntityMap<SecurityUser>
{
    public SecurityUserMap()
    {
        HasKey(p => p.Id);

        Property(p => p.LoginId)
            .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute{ IsClustered = true, IsUnique = true }))
            .HasMaxLength(SecurityUserValidator.MaxLoginIdLength).IsRequired();
        Property(p => p.DisplayName)
            .HasMaxLength(SecurityUserValidator.MaxDisplayNameLength).IsRequired();

        Property(p => p.Modified)
            .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute()));
    }
}

and

public class UserMembershipMap: EntityMap<UserMembership>
{
    public UserMembershipMap()
    {
        HasKey(p => p.Id);

        Property(p => p.UserGroupId)
            .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("UK_UserMembership", 1) { IsClustered = true, IsUnique = true }));
        Property(p => p.LoginId)
            .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("UK_UserMembership", 2) { IsClustered = true, IsUnique = true }))
            .HasMaxLength(UserMembershipValidator.MaxLoginIdLength).IsRequired();
        Property(p => p.SiteId)
            .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("UK_UserMembership", 3) { IsClustered = true, IsUnique = true }));

        Property(p => p.Modified)
            .HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute()));

        HasRequired(p => p.SecurityUser).WithMany(p => p.UserMemberships).Map(t => t.MapKey(new[] { "LoginId" }));
    }
}

来源:https://stackoverflow.com/questions/29963793/entity-framework-6-1-3-foreign-key-on-non-primary-key-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!