Magazine と Author (MM リレーションシップ) の 2 つのオブジェクトがあります。
public partial class MAGAZINE
{
public MAGAZINE()
{
this.AUTHORs = new HashSet<AUTHOR>();
}
public long REF_ID { get; set; }
public string NOTES { get; set; }
public string TITLE { get; set; }
public virtual REFERENCE REFERENCE { get; set; }
public virtual ICollection<AUTHOR> AUTHORs { get; set; }
}
public partial class AUTHOR
{
public AUTHOR()
{
this.MAGAZINEs = new HashSet<MAGAZINE>();
}
public long AUTHOR_ID { get; set; }
public string FULL_NAME { get; set; }
public virtual ICollection<MAGAZINE> MAGAZINEs { get; set; }
}
}
私の問題は、雑誌に対して著者の数を更新できないように見えることです。たとえば、「Smith, P.」という著者が 1 人いる場合などです。既に雑誌に対して保存されている場合、"Jones, D." という名前の別の名前を追加できますが、Edit コントローラーにポストバックした後も、著者の数は 1 と表示されます。つまり、"Smith, PH" です。
著者の数を親エンティティ(雑誌)にモデルバインドすることに成功したことに注意してください。カスタムモデルバインダーを使用して著者を取得し、マガジンにバインドします(私は思います)が、まだ更新されていないようですちゃんと。
モデルを更新するための私のコードは単純明快で、前後の変数値を示しています。
public ActionResult Edit(long id)
{
MAGAZINE magazine = db.MAGAZINEs.Find(id);
return View(magazine);
}
そして、ここに編集前/更新中の変数があります -
[HttpPost]
public ActionResult Edit(MAGAZINE magazine)
{
if (ModelState.IsValid)
{
db.Entry(magazine).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(magazine);
}
...そして、新しい作成者が追加された後の変数は次のとおりです...
私は、著者エンティティがどの雑誌にも拘束されていないことをポスト編集で示しているのではないかと疑っています。これが、雑誌エンティティに更新されていない理由だと推測しています。同じ雑誌エンティティ - 著者のカスタム モデル バインダーと関係があるのではないかと思います。
誰でもこの問題について助けることができますか?
完全を期すために - AuthorModelBinder クラスも含めました -
public class AuthorModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var values = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (values != null)
{
// We have specified asterisk (*) as a token delimiter. So
// the ids will be separated by *. For example "2*3*5"
var ids = values.AttemptedValue.Split('*');
List<int> validIds = new List<int>();
foreach (string id in ids)
{
int successInt;
if (int.TryParse(id, out successInt))
{
validIds.Add(successInt);
}
else
{
//Make a new author
AUTHOR author = new AUTHOR();
author.FULL_NAME = id.Replace("\'", "").Trim();
using (RefmanEntities db = new RefmanEntities())
{
db.AUTHORs.Add(author);
db.SaveChanges();
validIds.Add((int)author.AUTHOR_ID);
}
}
}
//Now that we have the selected ids we could fetch the corresponding
//authors from our datasource
var authors = AuthorController.GetAllAuthors().Where(x => validIds.Contains((int)x.Key)).Select(x => new AUTHOR
{
AUTHOR_ID = x.Key,
FULL_NAME = x.Value
}).ToList();
return authors;
}
return Enumerable.Empty<AUTHOR>();
}
}