0

I am building a project on ASP.Net for an assignment and I'm having trouble figuring out how to add the currently logged in user's Id which is a guid as a foreign key to know what items they are adding. I need to do this because when the user is logged in, they need to see their uploaded files only.

The following is the code that I have tried:

The Business Logic Layer:

    public void AddAudio(string title, string description, int genre, Guid userId, string filePath)
    {
        Audio i = new Audio();
        i.Title = title;
        i.Description= description;
        i.Genre_Id = genre;
        i.User.Id = userId;

        if (string.IsNullOrEmpty(filePath) == false)
            i.FilePath = filePath;

        new AudioRepository().AddAudio(i);
    }

The following is the Controller:

        public ActionResult Create(Audio i, HttpPostedFileBase fileData)
    {
        try
        {
            Logger.LogMessage("", Request.Path, "Entered the Create 
             Action");


            string uniqueFilename = Guid.NewGuid() + 
             Path.GetExtension(fileData.FileName);
            string absolutePath = Server.MapPath(@"\Audio") + @"\";
            fileData.SaveAs(absolutePath + uniqueFilename);




            i.FilePath = @"\Audio\" + uniqueFilename;


            new AudioBL().AddAudio(i.Title, i.Description,i.Genre_Id, 
             i.User.Id, i.FilePath);
            Logger.LogMessage("", Request.Path, "Finished adding the item in db");

            TempData["message"] = "Item added successfully";
            return RedirectToAction("Index");

        }

I have also added a picture of my Model so that you can understand my question better. : enter image description here

Mohan Rajput
  • 634
  • 9
  • 21
Burdy
  • 113
  • 10

1 Answers1

0

Your code look fine when you do i.User.Id = userId; that a relationship if that not works maybe your model not good or the data not correct, your model need to be something like this:

public class User
{
    [Key]
    public Guid Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }

    public string Email { get; set; }

    public string Password { get; set; }

    public string NoOfAttempts{ get; set;}

    public string Mobile { get; set; }

    public bool Blocked { get; set; }

    public ICollection<Audio> Audios { get; set; }
}

public class Audio
{
    [Key]
    public Guid Id { get; set; }

    public string Genre_Id {get;set;}

    public string Title { get; set; }

    public string Description { get; set; }

    public string FilePath { get; set; }

    //FK
    public Guid UserId { get; set; }

    public virtual User User { get; set; }
}
Liran
  • 323
  • 2
  • 16