C# 使用实体框架代码优先建模用户、好友请求和好友

C# Model User, Friend Requests and Friends with Entity Framework Code First(C# 使用实体框架代码优先建模用户、好友请求和好友)
本文介绍了C# 使用实体框架代码优先建模用户、好友请求和好友的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我之前在 SO 上问过一个关于类似主题的问题,但后来采取了不同的方法.这是我的模型:

I have previously asked a question here on SO about a similar topic but have since taken a different approach. This is my model:

public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole,CustomUserClaim>
{   
    public ApplicationUser()
    {
        Friends = new List<Friend>();
    }

    [Required]
    public string Alias { get; set; }

    public virtual ICollection<Friend> Friends { get; set; }
}

public class Friend
{
    public virtual int Id { get; set; }

    public virtual ApplicationUser RequestedBy { get; set; }

    public virtual ApplicationUser RequestedTo { get; set; }

    public DateTime? RequestTime { get; set; }

    public FriendRequestFlag FriendRequestFlag { get; set; }
}

public enum FriendRequestFlag
{
    None,
    Approved,
    Rejected,
    Blocked,
    Spam
};

我可以用这种方法添加朋友,当我从数据库中获取他们时他们会填充,示例:

I can add Friends with this approach and they populate when I get them from database, sample:

public void AddFriendRequest(ApplicationUser user, ApplicationUser friendUser)
{
    var friendRequest = new Friend()
    {
        RequestedBy = user,
        RequestedTo = friendUser,
        RequestTime = DateTime.Now,
        FriendRequestFlag = FriendRequestFlag.None
    };

    user.Friends.Add(friendRequest);
}

当我运行上面的代码时,执行后数据库中的朋友表是这样的:

When I run the code above, the friend table in the database looks like this after execution:

当我得到一个用户时,如果用户是 RequestedByRequestedTo,我不希望 Entity Framework 获取 Friend 中的所有行.这可能与EF有关吗?例如使用 Fluent API?我还想映射键以便不需要 [ApplicationUser_Id].

When I get a user I would wan't Entity Framework to get all rows in Friend were the user is either RequestedBy or RequestedTo. Is this possible to do with EF? For example with Fluent API? I would also like to map the keys so that [ApplicationUser_Id] is not needed.

推荐答案

@Mukesh 感谢您的回答,但我决定采用另一种方法,因为如果用户是 RequestedBy 或 RequestedTo,您的解决方案无法获取 Friend 中的所有行.这是我的解决方案:

@Mukesh thanks for your answer but I decided to take another approach since your solution did not get all rows in Friend were the user is either RequestedBy or RequestedTo. This is my solution:

public class ApplicationUser : IdentityUser<int, CustomUserLogin, CustomUserRole,
CustomUserClaim>
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager, string authenticationType)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
        // Add custom user claims here
        return userIdentity;
    }

    public ApplicationUser()
    {
        SentFriendRequests = new List<Friend>();
        ReceievedFriendRequests = new List<Friend>();
    }

    [Required]
    public string Alias { get; set; }

    public string Name { get; set; }

    public byte[] ProfilePicture { get; set; }

    public virtual ICollection<Friend> SentFriendRequests { get; set; }

    public virtual ICollection<Friend> ReceievedFriendRequests { get; set; }

    [NotMapped]
    public virtual ICollection<Friend> Friends {
        get
        {
            var friends = SentFriendRequests.Where(x => x.Approved).ToList();
            friends.AddRange(ReceievedFriendRequests.Where(x => x.Approved));
            return friends;
        } }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
    modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

    modelBuilder.Entity<Friend>()
        .HasRequired(a => a.RequestedBy)
        .WithMany(b => b.SentFriendRequests)
        .HasForeignKey(c => c.RequestedById);

    modelBuilder.Entity<Friend>()
        .HasRequired(a => a.RequestedTo)
        .WithMany(b => b.ReceievedFriendRequests)
        .HasForeignKey(c => c.RequestedToId);
}

public class Friend
{
    [Key, Column(Order = 0)]
    public int RequestedById { get; set; } 
    [Key, Column(Order = 1)]
    public int RequestedToId { get; set; } 
    public virtual ApplicationUser RequestedBy { get; set; }
    public virtual ApplicationUser RequestedTo { get; set; }

    public DateTime? RequestTime { get; set; }

    public DateTime? BecameFriendsTime { get; set; }

    public FriendRequestFlag FriendRequestFlag { get; set; }

    [NotMapped]
    public bool Approved => FriendRequestFlag == FriendRequestFlag.Approved;

    public void AddFriendRequest(ApplicationUser user, ApplicationUser friendUser)
    {
        var friendRequest = new Friend()
        {
            RequestedBy = user,
            RequestedTo = friendUser,
            RequestTime = DateTime.Now,
            FriendRequestFlag = FriendRequestFlag.None
        };
        user.SentFriendRequests.Add(friendRequest);
    }
}

public enum FriendRequestFlag
{
    None,
    Approved,
    Rejected,
    Blocked,
    Spam
};

这篇关于C# 使用实体框架代码优先建模用户、好友请求和好友的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)