从Orchard CMS中删除关系非内容数据

时间:2012-07-18 09:14:44

标签: asp.net-mvc asp.net-mvc-3 model-view-controller orchardcms

我通过定义记录和模式在Orchard CMS中声明了一些非内容数据:

public class CountyRecord
{
    public virtual int Id { get; set; }
    public virtual string CountyName { get; set; }
    public virtual CountryRecord CountryRecord { get; set; }
}

public class CountryRecord
{
    public CountryRecord()
    {
        CountyRecords = new List<CountyRecord>();
    }
    public virtual int Id { get; set; }
    public virtual string CountryName { get; set; }
    public virtual IList<CountyRecord> CountyRecords { get; set; }
}

public class Migrations: DataMigrationImpl
{
    public int Create()
    {
        //COUNTIES
        SchemaBuilder.CreateTable(typeof(CountyRecord).Name, table => table
            .Column<int>("Id", col => col
                .PrimaryKey()
                .Identity())
            .Column<string>("CountyName")
            .Column<int>("CountryRecord_Id"));

        //COUNTRIES
        SchemaBuilder.CreateTable(typeof(CountryRecord).Name, table => table
            .Column<int>("Id", col => col
                .PrimaryKey()
                .Identity())
            .Column<string>("CountryName"));
    }
}

然后我有两个控制器处理这两个实体的管理页面。在国家控制器中,我有以下行动:

    //DELETE
    [HttpGet, Admin]
    public ActionResult Delete(int countryId)
    {
        var country = CountryRepo.Get(countryId);
        if (country == null)
        {
            return new HttpNotFoundResult("Couldn't find the country with ID " + countryId.ToString());
        }
        return View(country);
    }

    [HttpPost, Admin, ActionName("Delete")]
    public ActionResult DeletePOST(CountryRecord country)
    {       
        foreach (CountyRecord county in CountyRepo.Fetch(c=>c.CountryRecord.Id==country.Id))
        {
            CountyRepo.Delete(county);
        }

        CountryRepo.Delete(country);
        OrchardServices.Notifier.Add(NotifyType.Information, T("Country '{0}' deleted successfully", country.CountryName));
        return RedirectToAction("Index");
    }

这是与之相关的观点:

@model Addresses.Models.CountryRecord
<div class="manage">
@using (Html.BeginFormAntiForgeryPost("Delete"))
{
    <h2>Are you sure you want to delete this country and ALL its counties?</h2>
    @Html.HiddenFor(m => m.Id);
    @Html.HiddenFor(m => m.CountryName);
    @Html.ActionLink(T("Cancel").Text, "Index", "CountriesAdmin", new { AreaRegistration = "Addresses" }, new { style = "float:right; padding:4px 15px;" })
    <button class="button primaryAction" style="float:right;">@T("Confirm")</button>
}
</div>

然而,这就是问题,当我删除仍有分配给它的县的国家时,会引发以下错误:

a different object with the same identifier value was already associated with the session

有人可以帮忙吗?

感谢。

1 个答案:

答案 0 :(得分:2)

这是因为您的DeletePOST()参数是CountryRecord。 Orchard记录全部由NHibernate框架代理,而MVC的ModelBinder无法为您正确创建它们。

您需要做的事情就像您在非POST方法中所做的那样:只接受CountryRecord的整数ID,从存储库中获取新记录,然后删除它。< / p>