如何将用户的Guid ID设置为他们正在创建的作为外键的项目?

时间:2018-11-18 08:28:04

标签: asp.net asp.net-mvc-5 foreign-keys guid

我正在ASP.Net上创建一个项目以进行分配,但是我很难弄清楚如何添加当前登录用户的ID(作为外键的GUID)以了解他们要添加的项目。我需要这样做,因为当用户登录时,他们只需要查看其上传的文件即可。

以下是我尝试过的代码:

业务逻辑层:

    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);
    }

以下是控制器:

        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");

        }

我还添加了我的模型的图片,以便您可以更好地理解我的问题。 : enter image description here

1 个答案:

答案 0 :(得分:0)

您的代码看起来不错 当您i.User.Id = userId;这样做时, 如果这不起作用,则可能是您的模型不好或数据不正确, 您的模型必须是这样的:

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; }
}