2016-07-19 12 views
0

私はMVCアプリケーションを持っています。私はEditメソッドに問題があります。データベースにポストバックしていません。私はブレークポイントを追加し、行ごとにステップし、値は更新されるようだが、データベースを更新していない。データベースにはプライマリIDフィールドはありませんが、その他のフィールド(username、service、short_plan、role)はすべてPKです。アイデア?編集はデータベースを更新していません

モデル:

[MetadataType(typeof(Department_RolesMetadata))] 
public partial class Department_Roles 
{ 
} 

public class Department_RolesMetadata 
{ 
    [Required] 
    public string username { get; set; } 
    [Required] 
    public string service { get; set; } 
    [Required] 
    public string short_plan { get; set; } 
    [Required] 
    public string role { get; set; } 
} 

コントローラー:

public ActionResult Edit(string username, string service, string sp, string role) 
    { 
     Department_Roles department_roles = db.Department_Roles.Where(dr => dr.username == username && dr.service == service && dr.short_plan == sp && dr.role == role).First(); 
     ViewBag.username = new SelectList(db.Service_Logins, "username", "user_type", department_roles.username); 
     return View(department_roles); 
    } 



    [HttpPost] 
    public ActionResult Edit(Department_Roles department_roles) 
    { 
     if (ModelState.IsValid) 
     { 

      db.Department_Roles.Attach(department_roles); 
      db.Entry(department_roles).State = System.Data.Entity.EntityState.Modified; 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 
     ViewBag.username = new SelectList(db.Service_Logins, "username", "user_type", department_roles.username); 
     return View(department_roles); 
    } 

ビュー:

@model NS.Models.Department_Roles 

@{ 
    ViewBag.Title = "Edit"; 
} 

<h2>Edit</h2> 

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> 

@using (Html.BeginForm()) { 
    @Html.ValidationSummary(true) 
    <fieldset> 
     <legend>Department</legend> 

     <div class="editor-label"> 
      @Html.LabelFor(model => model.username) 
     </div> 
    <div class="editor-field"> 
     @Html.DropDownListFor(model => model.username,NS.Models.Department_Roles.GetServiceLogins(),"--Select One--") 
     @Html.ValidationMessageFor(model => model.username) 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.service) 
    </div> 
    <div class="editor-field"> 
     @Html.DropDownListFor(model => model.service,NS.Models.Service_Logins.GetUserCompetitionTypes(),"--Select One--") 
     @Html.ValidationMessageFor(model => model.service) 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.short_plan) 
    </div> 
    <div class="editor-field"> 
     @Html.DropDownListFor(model => model.short_plan,NS.Models.FeeAuth.GetActiveShortPlans(),"--Select One--") 
     @Html.ValidationMessageFor(model => model.short_plan) 
    </div> 

    <div class="editor-label"> 
     @Html.LabelFor(model => model.role) 
    </div> 
    <div class="editor-field"> 
     @Html.DisplayFor(model => model.role) 
     @Html.HiddenFor(model => model.role) 
    </div> 

    <p> 
     <input type="submit" value="Save" /> 
    </p> 
</fieldset> 
} 

<div> 
    @Html.ActionLink("Back to List", "IndividualIndex", new { username = Model.username }) 
</div> 
+3

[Entity Framework 5のレコードを更新する]の可能な複製(http://stackoverflow.com/questions/15336248/entity-framework-5-updating-a-record) – Luke

+0

? – Luke

+0

いいえ、データベースのすべての値がPKである可能性があります。 – user2448412

答えて

0

プライマリキーを更新しようとしているので、これは動作していないという理由がありますデータベース内のレコードの値。 Entity Frameworkを使用してPK値を更新することは、レコードを識別するために使用されるため、更新できません。

私はあなたの主キーとしてIdフィールドを持っている示唆しているとあなたは以前にユニークであるためにあなたの主キーとして選択した列が必要な場合は、使用してデータベースにユニーク制約を追加することですこれらの列。この方法では、値がPK値にならないように値を更新することができ、データをそのまま維持するための一意の制約が適用されます。

あなたDepartment_RolesクラスにId値を追加し、この値のみを使用するようにPKを変更します。その後、

public class Department_Roles 
{ 
    // New Id value, this will be the primary key 
    public int Id { get; set; } 

    // ... 
} 

次に、あなたが選択したId値を持つレコードをチェックし、取得するためにこのような何かを書くことができますが存在し、

// Get an entity with all the required PK values 
// In your example this will be the posted Department_Roles object 
var departmentRole = new Department_Roles() { Id = 1 }; 

// Get the existing entry from the database 
var existingDepartmentRole = dbContext.Department_Roles.Find(departmentRole.Id); 

if (existingDepartmentRole == null) 
{ 
    throw new Exception("The existing department role could not be found using the PK values provided"); 
} 
else 
{ 
    // Update the entry that we got out of the database and update the values 
    existingDepartmentRole.username = "bob"; 
    existingDepartmentRole.role = "ProjectManager"; 
    existingDepartmentRole.service = "Management"; 
    existingDepartmentRole.short_plan = "permanant"; 

    // Save the changes 
    dbContext.SaveChanges(); 
} 
+0

私はこのコードを修正しようとしましたが、それでもデータベースは更新されません。 db.Department_Roles.Attach(department_roles); var updateRecord = db.Entry(department_roles);updateRecord.Property(u => u.short_plan)。IsModified = true; //db.Entry(department_roles).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); – user2448412

+0

何かをしているに違いありません、それはどんな種類の例外メッセージを引き起こしていますか? – Luke

+2

質問に追加のコードを追加してください:)。それをアタッチし、レコードを 'Modified'としてマークする場合は、個々のプロパティを 'IsModified = true'とマークする必要はありません。 – Luke

1

SQL PRIMARY KEY拘束:PRIMARY KEY制約は、一意のデータベーステーブル内の各レコードを識別する 行を更新します。 主キーにはUNIQUE値が含まれている必要があります。 主キー列にNULL値を含めることはできません。 ほとんどのテーブルはプライマリキーを持つ必要があり、各テーブルはプライマリキーを1つしか持てません。あなたのエッセンスを編集すると、実際には新しいものが作成されます! 4つのフィールドがすべてプライマリキーの場合複合プライマリキーです。コンポジットキーの外側にフィールドはありません。

+0

ルスラン、私は謝罪し、あなたがこれと正しい軌道に乗っていたことを認識したいと思います。行を識別するために使用されるため、Entity Frameworkを使用して主キーの値を更新することはできません。 – Luke

0

データベースからオブジェクトの古い値を取得し、EFのdbContext.Entry(oldObject).CurrentValues.SetValues(updatedValues)を使用して、そのあとSaveChnagesを呼び出しましたか? このmicrosoft articleは、このメソッドの使用方法を説明しています。

+0

私はEFのCurrentValues.SetValues()を使用しようとしましたが、値はまだ更新されませんでした。 – user2448412

関連する問題