我需要创建一个存储布尔值的变量。 is_following字段指示当前用户是否已签名(在其下进行授权)。我想要一个既好又快的解决方案。我的模型如下:
public class UserProfile
{
[Required]
public string FullName { get; set; }
public string Description { get; set; }
public int FollowerCount { get; set; } = 0;
public int FollowingCount { get; set; } = 0;
//I would like here to store a value to the status of subscription. This column must not be in the database.
public bool IsFollowing { get; set; } = false;
[Key]
public string UserId { get; set; }
[ForeignKey("UserId")]
[Required]
protected virtual ApplicationUser User { get; set; }
}
下表(模型):
public class Following
{
[Key, Column(Order = 0)]
public string UserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser User { get; set; }
[Key, Column(Order = 1)]
public string FollowerId { get; set; }
[ForeignKey("FollowerId")]
public virtual ApplicationUser FollowerUser { get; set; }
}
首先想到的是为每个请求提出额外请求:
var following = db.Followings.Any(u => u.FollowerId == uId && u.UserId == currentUserId);
我不适合,因为用户样本的整个项目,我都要做这个额外的请求。
更新:
[NotMapped]
public virtual bool Is_Following { get
{
var currentUser = HttpContext.Current.User.Identity.Name;
using (ApplicationDbContext db = new ApplicationDbContext())
{
var userid = db.Users.FirstOrDefault(u => u.UserName == currentUser);
if(userid!=null)
return db.Followings.Any(u => u.FollowerId == UserId && u.UserId == UserId);
}
return false;
}
至少如何使用当前上下文而不创建新的上下文。
答案 0 :(得分:0)
它可以帮助您轻松实现您的需求。
答案 1 :(得分:0)
它有效,但不是一个完美的解决方案:
[NotMapped]
public virtual bool Is_Following { get
{
var currentUser = HttpContext.Current.User.Identity.Name;
if (currentUser == null) return false;
using (ApplicationDbContext db = new ApplicationDbContext())
{
var userid = db.Users.FirstOrDefault(u => u.UserName == currentUser).Id;
if(userid!=null)
return db.Followings.Any(u => u.FollowerId == userid && u.UserId == UserId);
}
return false;
}
}