【问题标题】:Unable to cast object of type 'System.Data.Entity.DynamicProxies.ApplicationUser_xxxxxxxx' to type 'System.String'无法将“System.Data.Entity.DynamicProxies.ApplicationUser_xxxxxxxx”类型的对象转换为“System.String”类型
【发布时间】:2017-03-04 23:18:41
【问题描述】:

我正在尝试使用以下ActionResult将数据保存到数据库中

public ActionResult Create(GigFormViewModel viewModel)
    {
        var artistId = User.Identity.GetUserId();
        var artist = _context.Users.Single(u => u.Id == artistId);
        var genre = _context.Genres.Single(g => g.Id == viewModel.Genre);
        var gig = new Gig
        {
            Artist = artist,
            DateTime = DateTime.Parse(string.Format("{0} {1}", viewModel.Date, viewModel.Time)),
            Genre=genre,
            Venue=viewModel.Venue
        };
        _context.Gigs.Add(gig);
        _context.SaveChanges();
        return RedirectToAction("Index", "Home");

    }

保存数据时出现错误

无法将“System.Data.Entity.DynamicProxies.ApplicationUser_C811B05818B5E64ECDA3F7F75CC04ED97BE32CA9226F31FEEEF1EE499B74428B”类型的对象转换为“System.String”类型。

以下是更多详细信息的屏幕截图:

型号:

public class Genre
{
    public byte Id { get; set; }

    [Required]
    [StringLength(255)]
    public string Name { get; set; }
}

public class Gig
{
    public int Id { get; set; }

    [Required]
    [StringLength(255)]
    public ApplicationUser Artist { get; set; }

    [Required]
    public DateTime DateTime { get; set; }

    [Required]
    public string Venue { get; set; }

    [Required]
    public Genre Genre { get; set; }
}

可能是什么问题??

【问题讨论】:

  • 显示GigArtistVenueGenre的定义
  • 并在异常点发布调用栈:)
  • @haim770 我已经添加了我的模型类。

标签: c# sql entity-framework asp.net-mvc-5


【解决方案1】:

我自己想出来的。 我认为这是 Gigs 模型和Artist 验证的问题。 删除了数据注释[StringLength(255)],效果很好。

所以更新的 Gigs 模型类如下:

public class Gig
 {
public int Id { get; set; }

[Required]
[StringLength(255)]
public ApplicationUser Artist { get; set; }

[Required]
public DateTime DateTime { get; set; }

[Required]
public string Venue { get; set; }

[Required]
public Genre Genre { get; set; }
}

【讨论】:

    【解决方案2】:

    在我的情况下,这个完全相同的错误是由于 DateTime 对象没有识别我格式化传递给它的字符串的方式。

    我将时间输入为“9.05”(使用句点),而 DateTime 需要一个冒号“9:05”。

    Mosh 在视频中确实提到他假设输入有效,并且稍后会添加验证。因此,要克服这个障碍,请确保您的测试数据对 DateTime String Format 有效

    【讨论】:

      猜你喜欢
      • 2012-09-07
      • 2014-03-14
      • 2017-11-24
      • 1970-01-01
      • 2021-04-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多