【问题标题】:How to add collections of models to a model? (ASP.NET MVC3 with Entity Framework)如何将模型集合添加到模型中? (带有实体框架的 ASP.NET MVC3)
【发布时间】:2011-10-02 07:45:45
【问题描述】:

我正在使用代码优先的 Entity Framework 4 方法构建一个 ASP.NET MVC 3 站点。我的模型中有一个对象,Problem,它包含另一个模型对象 ProblemRating 的子集合。目前我的问题模型设置如下:

public class ProblemModel
{
    [Key]
    [Required]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ProblemId { get; set; }

    [Display(Name = "Creator")]
    [Required]
    public string UserName { get; set; }

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

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

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

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

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

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

    public virtual IEnumerable<ProblemRatingModel> Ratings { get; set; }

    public DateTime CreatedDate { get; set; }

    public DateTime LastModifiedDate { get; set; }
}

ProblemRating 类非常简单:

public class ProblemRatingModel
{
    [ForeignKey("AssociatedProblem")]
    public int AssociatedProblemId { get; set; }
    public ProblemModel AssociatedProblem { get; set; }
    public string UserName { get; set; }
    public decimal Rating { get; set; }
}

当我填写字段并单击“创建”时,控制器的 Create 方法中的样板代码未报告有效模型:

if (ModelState.IsValid)
{
    db.ProblemModels.Add(problemmodel);
    db.SaveChanges();
    return RedirectToAction("Index");  
}

return View(problemmodel);

在另一个模型类中处理模型的子集合的正确方法是什么?我也不是 100% 确定 ForeignKey 属性的用法,我正确使用了吗?

谢谢!

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 entity-framework


    【解决方案1】:

    如下更改您的 ProblemModel 类

    public class Problem //Renamed to Problem
    {
        ...
    
        public virtual ICollection<ProblemRating> Ratings { get; set; }
    
        ...
    }
    

    ...在您的 ProblemRating vlass 中执行以下操作

    public class ProblemRating // Renamed to ProblemRating
    {
        public int Id { get; set; } 
        public int ProblemId { get; set; }
        public string UserName { get; set; }
        public decimal Rating { get; set; }
    
        public virtual Problem Problem { get; set; }
    
    }
    

    EF 代码优先(方便的命名假设)将为您完成剩下的工作。

    看看这个 http://weblogs.asp.net/scottgu/archive/2010/07/16/code-first-development-with-entity-framework-4.aspx

    您还可以删除问题 ID 列上的关键属性

    【讨论】:

    • 非常感谢,我得到了它的工作。我没有意识到实体框架会根据它们的名称自动将某些属性视为 ID。那么数据注解属性如果不遵循我接受的内置EF命名约定可以使用吗?
    • 正确。如果您需要它们,它们就在那里,但 90% 的时间框架会为您解决问题
    • 太好了,谢谢。还有一个问题......现在我在将新项目保存到数据库之前在代码中手动设置 CreatedDate 和 LastModifiedDate。这里有更好的做法吗?我应该设置某种时间戳数据注释属性吗?
    猜你喜欢
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多