简体   繁体   English

实体框架 6:实体和关系

[英]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.我正在尝试使用 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. 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.通过前端 web 页面将一些电影添加到数据库后,在 addmovie web 页面中,我可以 select 其中一个由下拉列表创建,并且当我保存电影时,其中一个总是在里面创建的电影空的。 What am I doing wrong?我究竟做错了什么?

The Model is wrong Model 是错误的

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然后你可以在 select 列表中显示演员姓名时,您可以 select 将演员 ID 作为键

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在您的 html 下删除它,因为 Id 已附加到下拉列表中

 <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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 实体框架:ObjectSet attach(),具有多个关系的实体 - Entity Framework: ObjectSet attach(), entities with multiple relationships 更新具有与其他实体的多个关系的实体框架实体 - Update entity framework entity with multiple relationships to other entities 实体框架5添加具有其他外键关系的实体和子实体 - Entity Framework 5 add entity and child entities with other foreign key relationships 在实体框架核心中使用一对多关系更新连接的实体 - Updating connected entities with one-to-many relationships in entity framework core 实体框架代码优先关系:一对多到多个实体 - Entity Framework Code First Relationships: One to Many to Multiple Entities Entity Framework Core 不支持具有多对多关系的通用抽象实体 - Entity Framework Core not supporting generic abstract entities with many to many relationships 实体框架:处理两个实体之间的多个关系 - Entity Framework : Handle multiple relationships between two entities 插入与现有实体有关系的新实体时出现的问题(Entity Framework Core 1.1.0) - Issue when inserting new entity with relationships to existing entities (Entity Framework Core 1.1.0 ) 实体框架关系 - Entity framework relationships 实体框架中的三元关系 - Ternary relationships in Entity Framework
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM