質問

I am doing a project for my course work, I am using database first entity framework and got my DBContext class as

public partial class StudentDBEntities : DbContext
    {
         public DbSet<LoginDetail> LoginDetails { get; set; }
        public DbSet<StudentDetail> StudentDetails { get; set; }
        public DbSet<UserFriend> UserFriends { get; set; }
}

Now I created a model object as below to use this model to pass on view.

public class ViewStudentDetail
    {    
        public StudentDetail Student { get; set; }
        public UserFriend Friends { get; set; }

    }

here is my StudentDetail class created default

public partial class StudentDetail
    {
        public StudentDetail()
        {
            this.UserFriends = new HashSet<UserFriend>();
        }
        public string StudentName { get; set; }
        public string UnivName { get; set; }
        public string City { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
        public string EmailId { get; set; }

        public virtual ICollection<UserFriend> UserFriends { get; set; }
    }

In my View I have find a friend scenario and text box value passed is ViewStudentDetail.Friends.username.to the post method

My problem is that I want to assign the StudentDetails with the given username from DbContext object (that are already saved in database during registration) to the model object In My controller i have like this

  StudentDBEntities DbAccess = new StudentDBEntities();
 ViewStudentDetail Studentdetails = new ViewStudentDetail();
    Studentdetails.Student = DbAccess.StudentDetails .Find(username);

This assignment is not working and is assigning null. Could you please tell me how to fetch the values in db to model object. Also if i need to assign each attribute to model please help me with the syntax to fetch from db object.

役に立ちましたか?

解決

The DbSet.Find() method searches only for PRIMARY KEY matches, it will not search all/any properties on an entity.

I think you are looking for something like this:

ViewStudentDetail.Student = DbAccess.StudentDetails.FirstOrDefault(student => student.Username == username);

If not, please provide more of your source code in your question. Specifically, please include the generated entity classes.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top