ASP MVC表的外键配置

时间:2013-03-24 19:09:52

标签: asp.net-mvc

public class Movies
{
    [Key]
    public int movieID { get; set; }

    public String Title { get; set; }

    public virtual Genres parentGenre { get; set; }
}


public class Genres
{
    public Genres()
    {
        this.movies = new HashSet<Movies>();
    }

    [Key]
    public int genreId { get; set; }

    public String genreName { get; set; }

    public ICollection<Movies> movies { get; set; }
}

我可以通过阅读Genres表在addmovie视图页面上成功创建DropDownList。

但是当我尝试提交页面时,它会声明“值'10'无效。”这让我相信我正在尝试将Int(从下拉列表值)放入一个对象(来自“Genres parentGenre”)。

我是否将“genres parentGenre”设置为“genreId”外键关系正确地设置为只需要“parentGenre”字段的“数字”,或者它是否期望更多?

加入:

控制器:

    [HttpPost]
    public ActionResult Create(Movies movies)
    {
        if (ModelState.IsValid)
        {
            db.Movies.Add(movies);
            db.SaveChanges();
            return RedirectToAction("Index");  
        }
        IEnumerable<SelectListItem> items = db.Genres
            .Select(c => new SelectListItem
                            {
                                Value = SqlFunctions.StringConvert((double)c.genreId).Trim(),
                                Text = c.genreName
                            });
        ViewBag.genreId = items;
    }

视图:

    <div class="editor-label">
        @Html.LabelFor(model => model.parentGenre.genreName)
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(model => model.parentGenre,(IEnumerable<SelectListItem>)ViewBag.genreId)
        @Html.ValidationMessageFor(model => model.parentGenre)

1 个答案:

答案 0 :(得分:1)

代替您的评论,这是我推荐的内容:

型号:

public class Movie
    {
        [Key]
        public int MovieID { get; set; }

        public String Title { get; set; }

        public int GenreId { get; set; }

        public virtual Genre Genre { get; set; }
}

public class Genre
{
    public Genre()
    {
        this.movies = new HashSet<Movies>();
    }

    [Key]
    public int GenreId { get; set; }

    public String Name { get; set; }

    public ICollection<Movies> Movies { get; set; }
}

控制器:

[HttpPost]
public ActionResult Create(Movie Movie)
{
    if (ModelState.IsValid)
    {
        db.Movies.Add(Movie);
        db.SaveChanges();
        return RedirectToAction("Index");  
    }
    IEnumerable<SelectListItem> items = db.Genres
        .Select(c => new SelectListItem
                        {
                            Value = SqlFunctions.StringConvert((double)c.GenreId).Trim(),
                            Text = c.Name
                        });
    ViewBag.genreId = items;
}

查看:

<div class="editor-label">
    @Html.LabelFor(model => model.Genre.Name)
</div>
<div class="editor-field">
    @Html.DropDownListFor(model => model.Genre.Id,(IEnumerable<SelectListItem>)ViewBag.genreId)
    @Html.ValidationMessageFor(model => model.Genre)
</div>

如果我正在阅读您正在做的事情,那应该可行。我对EF做的并不多,所以我不能100%肯定。