Click here to Skip to main content
16,019,055 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I have model class like this, I want to use FromUserId and ToUserId as foreign keys for UserProfile table.
public class Chat
    {
        [Key]
        public int MessageId { get; set; }
        [Required]
        public int FromUserId { get; set; }
        [Required]
        public int ToUserId { get; set; }
        [Required]
        public string Message { get; set; }
        [Required]
        public DateTime Time { get; set; }
        
        public virtual ICollection<UserProfile> UserProfiles { get; set; }
    }


Is that even possible ? If it's not could you look at this? I got unspecified error at
var name = db.UserProfiles.Find(2);
. I think it's caused because I try to access a DB while it's already accessed.
public void getMessages()
       {
           var db = new UsersContext();
           var messages = from a in db.Messages where a.FromUserId== WebSecurity.CurrentUserId || a.ToUserId==WebSecurity.CurrentUserId select a;

           foreach(var a in messages)
           {
               if (a.FromUserId == WebSecurity.CurrentUserId)
               {
                   Clients.Caller.addNewMessageToPage(WebSecurity.CurrentUserName, a.Message);
               }
               else
               {
                   var name = db.UserProfiles.Find(2);
                   Clients.Caller.addNewMessageToPage(name.UserName, a.Message);
               }
           }
           db.Dispose();

       }
Posted
Comments
Member 9507975 26-Sep-13 21:31pm    
firstly you dont need to do

if (a.FromUserId == WebSecurity.CurrentUserId)
{

becuase at the top u are only seleecting the ones which pass this

from a in db.Messages where a.FromUserId== WebSecurity.CurrentUserId || a.ToUserId==WebSecurity.CurrentUserId select a;

maybe this line
db.UserProfiles.Find(2);

is throwing error because a userprofile with id 2 does not exist

1 solution

As someone said, when you search, you should check you found something before working with it. You can have as many foreign keys as you like, that's not your issue. Any errors you get, copy them exactly in to your question. Also tell us the exact line that blows up and the state of any variables it uses.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900