user3622910
user3622910

Reputation: 47

Select query in Entity framework

I have two models and a dbcontext:

public class User
{
    public int UserId { get; set; }
    public String UserName { get; set; }
    public virtual ICollection<Conversation> Conversations { get; set; } 
}

public class Conversation
{
    public int ConversationId { get; set; }
    public String Text { get; set; }
    public int UserId { get; set; }
    public virtual User User { get; set; }
}

public class ChatContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Conversation> Conversations { get; set; }    
}

I am trying to add a conversation entity so I need to retrieve the UserId from User table. So far I have:

var newtext = new Conversation()
{
    Text = message, // message is sent from user
    UserId = ChatContext.User.Where(u => u.UserName == name).Select(u => u.UserId)  
};

I need to query the user table to retrieve the userId associated with that particular name. How should I achieve this? The error is:

ChatContext does not have a definition for user.

Upvotes: 0

Views: 78

Answers (1)

Salah Akbari
Salah Akbari

Reputation: 39946

Firstly: You must add static to Users like this:

public class ChatContext : DbContext
{
   public static DbSet<User> Users { get; set; }
   public DbSet<Conversation> Conversations { get; set; }
}

Secondly: You must add FirstOrDefault method to your query, Because it will return an iQueryable like this:

var newtext = new Conversation()
{
   Text = message, // message is sent from user
   UserId = ChatContext.Users.FirstOrDefault(u => u.UserName == name).UserId
};

This should works.

Upvotes: 1

Related Questions