简体   繁体   中英

Entity Framework 6: entities and relationships

I am a solo and very beginner learner. I am trying to create a simple code first app with a database using EF6. I cannot understand how to insert the data of a entity inside another by the frontend. I have two entities:

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

    public string Title{ get; set; }  

    public int ActorId { get; set; }

    public ICollection<Actor> Actors { get; set; }    
}
public class Actor
{
    [Key]
    public int Id { get; set; }

    public string Name { get; set; }

    [ForeignKey("MovieId")]
    public ICollection<Movie> Movies { get; set; }
}

The controller.

public ActionResult AddMovie()
{
    var actorsList = (from Name in ctx.Attors select Name).ToList();
    ViewBag.Actors = new SelectList(actorsList, "Name", "Name");
    return View(new Film());
}

[HttpPost]
public ActionResult PerformAddMovie(Movie m)
{
    try
    {
        ctx.Movies.Add(m);
        ctx.SaveChanges();
        return RedirectToAction("Index", "Home");
    }
    catch(Exception ex)
    {
        ModelState.AddModelError("", ex.Message);
    }
    return RedirectToAction("Index", "Home");
}
@model Cinema.Models.Movie
    
@{
    ViewBag.Title = "AddMovie";
}

<h2>AddFilm</h2>

@{ 
    var list = ViewBag.Actors as SelectList;
}


@using (Html.BeginForm("PerformAddMovie", "Movie", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    
<div class="form-horizontal">
    <h4>Film</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.ActorId, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.ActorId, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.ActorId, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Actors, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(m => m.Actors, list, "---Select---", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Actors, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
    }
    <div>
        @Html.ActionLink("Back to List", "Index")
    </div>

    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
    }

After adding some movies into the database by the frontend web page, in the addmovie web page I can select one of them by the dropdown list, but when I save the movie nothing happens inside the third table created with movieid and actorid, it is always empty. What am I doing wrong?

The Model is wrong

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

    public string Title{ get; set; }  

    public int ActorId { get; set; }

    public virtual Actor Actor { get; set; }    // It should be one to one relationship
}

public class Actor
{
[Key]
public int Id { get; set; }

public string Name { get; set; }

//[ForeignKey("MovieId")]    This is unneccessary
public ICollection<Movie> Movies { get; set; }
}

Then u can select the Actor Id as key while display actor name in the select list

ViewBag.Actors = new SelectList((from s in db.Actor 
                                 select new {Id = s.Id, Name = s.Name }), 
                                  "Id", "Name");

Remove this under your html as the Id is attached to the dropdown list

 <div class="form-group">
        @Html.LabelFor(model => model.ActorId, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.ActorId, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.ActorId, "", new { @class = "text-danger" })
        </div>
    </div>

change the dropdownlist to this

<div class="form-group">
        @Html.LabelFor(model => model.ActorId, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownListFor(m => m.ActorId, (Selectlist)ViewBag.Actor, "---Select---", new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.ActorId, "", new { @class = "text-danger" })
        </div>
    </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM