2016-10-18 6 views
1

ブール値を格納する変数を作成する必要があります。 is_followingフィールドは、現在のユーザが署名されている(認可されている)かどうかを示します。私は素早く素敵な解決策を望んでいます。次のように私のモデルは以下のとおりです。次の表Entity Frameworkモデルの追加クエリ

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; } 
} 

(MODEL):

var following = db.Followings.Any(u => u.FollowerId == uId && u.UserId == currentUserId); 

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; } 
} 

心に来る最初の事は、すべての要求のための追加的な要求をすることです私は適切ではない、全体のプロジェクトは、ユーザーのサンプルは、私はこの追加の要求を行う必要があるためです。

UPDATE:あなたは新しいものを作成せずに現在のコンテキストを使用することができ、少なくともどのよう

[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

それは動作しますが、ない完璧なソリューション:

[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; 
     } 
    } 
0

リポジトリパターンについて読んだことはありますか? https://www.asp.net/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

これは、必要なものをすばやく簡単に実装するのに役立ちます。

+0

はい、それは私が持っているし、実施するものです。しかし、それは私の仕事には適していない、私はテーブルからデータを取得したい "次の"は、ユーザー取得(テーブル "UserInfo")と一緒に開催されました。私の記録のトップへの更新、私は望んでいたと付け加えました。 – Feanon

関連する問題