不能将类型“int”隐式转换为类型“Blogosphere.Models.Users”

本文关键字:类型 Blogosphere Users Models 转换 int 不能 | 更新日期: 2023-09-27 18:32:12

大家好,

我已经搜索并搜索了如何做到这一点。

我有一个名为帖子的域模型.cs下面

public class Posts
{
    [Key]
    public int PostID { get; set; }
    [Required(ErrorMessage="A Title is required for your Post")]
    [Display(Name="Title")]
    public string PostTitle { get; set; }

    [Required(ErrorMessage="This Field is Required")]
    [Display(Name = "Post")]
    public string PostContent { get; set; }
    [Required()]
    [DataType(DataType.DateTime)]
    public DateTime PostDate { get; set; }
    //public int AuthorID { get; set; }
    //public int CommentID { get; set; }
    [NotMapped]
    public virtual List<Comments> Comment { get; set; }
    public virtual Users user { get; set; }
}

所以我创建了一个名为 PostsVM 的视图模型.cs以便将其呈现给视图并获取 PostTitle 和 PostContent,因为它们是唯一需要编辑的字段

public class PostsVM
{
    [Required()]
    [Display(Name="Title")]
    public string PostTitle { get; set; }
    [Required()]
    [Display(Name="Post")]
    public string PostContent { get; set; }
}

由于帖子属于用户,因此该行

public virtual Users user { get; set; }

在帖子.cs类中。也就是说,当我将帖子保存到数据库时,我必须将其与作为帖子作者的用户ID一起保存。我的控制器看起来像这样

[HttpGet]
public ActionResult Create()
{
    PostsVM model = new PostsVM();
    return View(model);
}

[HttpPost]
public ActionResult Create(PostsVM model)
{
    if (!ModelState.IsValid)
    {
        ModelState.AddModelError("", "Invalid Model");
    }
    BlogContext db = new BlogContext();
    var newPost = db.Post.Create();
    newPost.PostTitle = model.PostTitle;
    newPost.PostContent = model.PostContent;
    newPost.PostDate = DateTime.Now;
    FormsIdentity identity = (FormsIdentity)User.Identity;
    int nUserID = Int32.Parse(identity.Ticket.UserData);
    newPost.user = Int32.Parse(identity.Ticket.UserData);
    db.Post.Add(newPost);
    db.SaveChanges();
    return RedirectToAction("Index", "Posts");
}

试图做的是从我存储在票证中的用户数据中获取 userId,并将其转换为行中的整数类型

newPost.user = Int32.Parse(identity.Ticket.UserData);

但是,上面的这条线显示为一条红色波浪线,错误"Cannot implicitly convert type 'int' to type 'Blogosphere.Models.Users'. 所以我试着这样做

newPost.user.UserID = Int32.Parse(identity.Ticket.UserData);

但是我在此行上调试了一个断点,并且收到一个错误,说

"Object reference not set to an instance of an object."

我知道这样做是错误的,因为它将访问 User.cs 类的所有属性。请问我如何在我存储在票证中的用户数据中获取用户 ID 并将其保存在

public virtual Users user { get; set; } property of the Posts.cs class?

请有人帮忙。StackOverflow非常有帮助。请?

不能将类型“int”隐式转换为类型“Blogosphere.Models.Users”

newPost.user 属性未初始化,访问newPost.user.UserID将引发"对象引用未设置为对象的实例"。