1

实际上,我正在研究简单的项目 MVC4 + EF,其中我有关系应用程序许可证。在应用程序上可能有零个或多个许可证,但每个许可证只有一个应用程序。我注意到操作编辑/创建新许可证存在一些问题。我过去了部分代码。

我的实体域定义:

public class Application
{
    public Application()
    {
        Licenses = new List<License>();
    }

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public Guid ApplicationID { get; set; }

    public string Name { get; set; }

    public List<License> Licenses { get; set; }
}

public class License
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [HiddenInput(DisplayValue = false)]
    public Guid LicenseID { get; set; }

    [Required]
    public string Name { get; set; }

    public Version Version { get; set; }

    public Application Application { get; set; }
}

应用程序和许可证之间的一对多定义:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Application>()
        .HasMany(app => app.Licenses)
        .WithRequired()
        .Map(conf => conf.MapKey("OwnerID"))
        .WillCascadeOnDelete(false);

    modelBuilder.Entity<License>()
        .HasRequired(lic => lic.Application)
        .WithMany()
        .Map(conf => conf.MapKey("ApplicationID"))
        .WillCascadeOnDelete(false);
}

许可证控制器中的操作:

public ActionResult Create(Guid applicationID)
{
    var application = repositoryApps.Applications.FirstOrDefault(a => a.ApplicationID == applicationID);

    var license = new License {Application = application};
    application.Licenses.Add(license);

    return View("Edit", license);
}

public ActionResult Edit(License license)
{
    return View(license);
}

[HttpPost]
public ActionResult Save(License license)
{
    if(ModelState.IsValid)
    {
        repositoryLics.SaveLicense(license);
        TempData["message"] = string.Format("{0} has been saved", license.Name);

        return RedirectToAction("Index", "Application");
    }
    else
    {
        return View("Edit", license);
    }
}

编辑fincense的视图:

@using (Html.BeginForm("Save", "License"))
{
    @Html.EditorForModel(Model);

    <input type="submit" value="Save" class="btn btn-primary"/>

    @Html.ActionLink("Cancel", "Index", "Application", null, new {@class = "btn"})
}

我在创建新许可证时遇到问题。我正在调用操作 Create 并将其传递给它的父 ApplicationID。经过一些准备后,我将许可证实例传递给编辑视图,在该视图中可以编辑新创建的对象。在编辑视图(许可证)中,一切似乎都很好。我有一个非空字段应用程序的许可证(我在其中收集了许可证)。当我提交编辑表单时,我将返回操作保存(许可证)。不幸的是,在这个地方属性 Application 等于 null,所以我错过了新创建的许可证和父应用程序之间的关系。

有没有人建议我如何避免这个问题?我应该如何存储新创建的许可证对象?我会感谢任何提示或建议。

问候,
格热戈日

4

1 回答 1

1

我在你的课上看不到ApplicationID财产License!!???

您应该添加此属性并将其添加到 EditorTemplate 中,如果您愿意,可能会隐藏。顺便说一句,将您的问题添加License EditorTemplate到您的问题中,让我们知道。

于 2012-05-23T08:06:22.053 回答