D
D
Denis Goncharenko2016-12-12 10:33:57
ASP.NET
Denis Goncharenko, 2016-12-12 10:33:57

How to specify parent for child model?

There is one model:

public class User
    {
        [Key]
        public int Id { get; set; }
        public string Email { get; set; }
        public string  FirstName{ get; set; }
        public string LastName { get; set; }
        public string Password { get; set; }
        public int CreatedAt { get; set; }
        public ICollection<Video> Videos { get; set; }
    }

and another:
public class Video
    {
        [Key]
        public int Id { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public string File { get; set; }
        public string Hash { get; set; }
        public int CreatedAt { get; set; }
        public int Views { get; set; }
    }

Communication one-many as you understand. And so, by means of codefirst'a it is all filled in in a DB.
And everything is fine, the User_Id field is automatically created in the Videos table, but damn it, how to fill this field?
That is, when adding a video, how to specify its author? Well, that is, there is a column in the table, but this field is not in the model, so it doesn’t work like this:
VideosRep.Add(new Video()
                {
                    Title = videoTitle,
                    File = FileName,
                    Description = videoDescription,
                    Hash = HashString,
                    CreatedAt = MyHelpers.GetUtcTimeStamp(),
                    User_Id = /// ругается на отсутствие поля у модели оно и понятно
                }
            );

Added a field to the video model
public User User { get; set; }
But when adding a video:
VideosRep.Add(new Video()
{
Title = videoTitle,
File = FileName,
Description = videoDescription,
Hash = HashString,
CreatedAt = MyHelpers.GetUtcTimeStamp(),
User = UsersRep.Users.Where(c => c.Id == userId).First()
}
);

A new user is created in the table, why???

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question