MVC 2实体框架视图模型插入 [英] MVC 2 Entity Framework View Model Insert

查看:99
本文介绍了MVC 2实体框架视图模型插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是推动我疯了。希望我的问题是有道理的......

This is driving me crazy. Hopefully my question makes sense...

我使用MVC 2和Entity Framework 1,我试图插入新记录有两个导航属性​​。

I'm using MVC 2 and Entity Framework 1 and am trying to insert a new record with two navigation properties.

我有一个SQL表,关键字,具有查找表CategoryTypes和另一个自参照查找CategoryParent。 EF使我的分类模型中的两个导航属性​​,一个叫父母和另一个叫CategoryType,各自车型的两个实例。

I have a SQL table, Categories, that has a lookup table CategoryTypes and another self-referencing lookup CategoryParent. EF makes two nav properties on my Category model, one called Parent and another called CategoryType, both instances of their respective models.

在我的观点,即创建新的类别,我有两个下拉菜单,一个用于CategoryType,另一个用于ParentCategory。当我尝试插入新的类别没有ParentCategory,这使得空,一切都很好。当我加入ParentCategory,插入失败,奇怪的(或因此我认为)抱怨此错误的形式CategoryType:

On my view that creates the new Category, I have two dropdowns, one for the CategoryType and another for the ParentCategory. When I try and insert the new Category WITHOUT the ParentCategory, which allows nulls, everything is fine. As soon as I add the ParentCategory, the insert fails, and oddly (or so I think) complains about the CategoryType in the form of this error:

相关'CategoryTypes被发现了。 1'CategoryTypes'的预期。

0 related 'CategoryTypes' were found. 1 'CategoryTypes' is expected.

当我步,我可以verifiy这两个ID属性来在行动方法的参数是正确的。我还可以验证,当我去到数据库来获取CategoryType和ParentCategory用的ID,该记录被拉到罚款。然而,失败的SaveChanges上()。

When I step through, I can verifiy that both ID properties coming in on the action method parameter are correct. I can also verify that when I go to the db to get the CategoryType and ParentCategory with the ID's, the records are being pulled fine. Yet it fails on SaveChanges().

所有我能看到的是,在我看来,我的CategoryParent dropdownlistfor,以某种方式导致插入轰炸。

All that I can see is that my CategoryParent dropdownlistfor in my view, is somehow causing the insert to bomb.

请看看我的意见,我httpPost创建操作方法。

Please see my comments in my httpPost Create action method.

我的视图模型是这样的:

My view model looks like this:

public class EditModel
{
    public Category MainCategory { get; set; }
    public IEnumerable<CategoryType> CategoryTypesList { get; set; }
    public IEnumerable<Category> ParentCategoriesList { get; set; }
}

我创建的操作方法是这样的:

My Create action methods look like this:

// GET: /Categories/Create
    public ActionResult Create()
    {
        return View(new EditModel()
        {
            CategoryTypesList = _db.CategoryTypeSet.ToList(),
            ParentCategoriesList = _db.CategorySet.ToList()
        });
    }

    // POST: /Categories/Create
    [HttpPost]
    public ActionResult Create(Category mainCategory)
    {
        if (!ModelState.IsValid)
            return View(new EditModel()
            {
                MainCategory = mainCategory,
                CategoryTypesList = _db.CategoryTypeSet.ToList(),
                ParentCategoriesList = _db.CategorySet.ToList()
            });

        mainCategory.CategoryType = _db.CategoryTypeSet.First(ct => ct.Id == mainCategory.CategoryType.Id);

        // This db call DOES get the correct Category, but fails on _db.SaveChanges().
        // Oddly the error is related to CategoryTypes and not Category.
        // Entities in 'DbEntities.CategorySet' participate in the 'FK_Categories_CategoryTypes' relationship.
        // 0 related 'CategoryTypes' were found. 1 'CategoryTypes' is expected.
        //mainCategory.Parent = _db.CategorySet.First(c => c.Id == mainCategory.Parent.Id);

        // If I just use the literal ID of the same Category,
        // AND comment out the CategoryParent dropdownlistfor in the view, all is fine.
        mainCategory.Parent = _db.CategorySet.First(c => c.Id == 2);

        _db.AddToCategorySet(mainCategory);
        _db.SaveChanges();

        return RedirectToAction("Index");
    }

下面是我在视图中创建表单:

Here is my Create form on the view :

    <% using (Html.BeginForm()) {%>
    <%= Html.ValidationSummary(true) %>

    <fieldset>
        <legend>Fields</legend>

        <div>
            <%= Html.LabelFor(model => model.MainCategory.Parent.Id) %>
            <%= Html.DropDownListFor(model => model.MainCategory.Parent.Id, new SelectList(Model.ParentCategoriesList, "Id", "Name")) %>
            <%= Html.ValidationMessageFor(model => model.MainCategory.Parent.Id) %>
        </div>

        <div>
            <%= Html.LabelFor(model => model.MainCategory.CategoryType.Id) %>
            <%= Html.DropDownListFor(model => model.MainCategory.CategoryType.Id, new SelectList(Model.CategoryTypesList, "Id", "Name"))%>
            <%= Html.ValidationMessageFor(model => model.MainCategory.CategoryType.Id)%>
        </div>

        <div>
            <%= Html.LabelFor(model => model.MainCategory.Name) %>
            <%= Html.TextBoxFor(model => model.MainCategory.Name)%>
            <%= Html.ValidationMessageFor(model => model.MainCategory.Name)%>
        </div>

        <div>
            <%= Html.LabelFor(model => model.MainCategory.Description)%>
            <%= Html.TextAreaFor(model => model.MainCategory.Description)%>
            <%= Html.ValidationMessageFor(model => model.MainCategory.Description)%>
        </div>

        <div>
            <%= Html.LabelFor(model => model.MainCategory.SeoName)%>
            <%= Html.TextBoxFor(model => model.MainCategory.SeoName, new { @class = "large" })%>
            <%= Html.ValidationMessageFor(model => model.MainCategory.SeoName)%>
        </div>

        <div>
            <%= Html.LabelFor(model => model.MainCategory.HasHomepage)%>
            <%= Html.CheckBoxFor(model => model.MainCategory.HasHomepage)%>
            <%= Html.ValidationMessageFor(model => model.MainCategory.HasHomepage)%>
        </div>

        <p><input type="submit" value="Create" /></p>
    </fieldset>

<% } %>

也许我刚刚熬夜太晚摆弄MVC 2? :)请让我知道如果我不是足够清晰。

Maybe I've just been staying up too late playing with MVC 2? :) Please let me know if I'm not being clear enough.

有些事情我已经因为提出这个问题改变。我想我关门?

我的新创建的操作方法:

My new Create action method:

        private DbEntities _db = new DbEntities();

    // POST: /Categories/Create
    [HttpPost]
    public ActionResult Create(Category mainCategory)
    {
        if (!ModelState.IsValid)
            return View(new EditModel()
            {
                MainCategory = mainCategory,
                CategoryTypesList = _db.CategoryTypeSet.ToList(),
                ParentCategoriesList = _db.CategorySet.ToList()
            });

        int parentId = 2; // Accessories in db.
        short typeId = 1; // Product type in db.
        mainCategory.ParentReference.EntityKey = new EntityKey("DbEntities.CategorySet", "Id", parentId);
        mainCategory.CategoryTypeReference.EntityKey = new EntityKey("DbEntities.CategoryTypeSet", "Id", typeId);

        _db.AddToCategorySet(mainCategory);     
        _db.SaveChanges();

        return RedirectToAction("Index");
    }

我也注释掉我的两个dropdownlists等mainCategory这些属性不被实例化。

I've also commented out my two dropdownlists so those properties on "mainCategory" don't get instantiated.

所以,用2导航属性现在空的,我用两个文字为ID的,它完美的作品。最后,我想用从mainCategory父母CategoryType的标识的,但这似乎不工作。可能是一个很好的理由,我不知道的?

So, with the 2 nav properties null now, I use two literals for the Id's and it works perfectly. Ultimately, I want to use the Id's of Parent and CategoryType from mainCategory, but this seems to not work. Probably a good reason I'm not aware of?

推荐答案

你有没有尝试设置的EntityReference像

Did you try setting the EntityReference like

mainCategory.CategoryTypeReference.EntityKey = new EnityKey("YourEntities", "Id", mainCategory.CategoryType.Id);

这样你不会有加载您CategoryType它可能会解决你的问题。

that way you wont have to load your CategoryType and it might resolve your problem.

修改:我张贴的样本是不完整的,对不起,这里是你应该做的。

EDIT: The sample i posted is not complete, sorry, here is what you should do

int parentId = mainCategory.Parent.Id; 
short typeId = mainCategory.CategoryType.Id;

mainCategory.Parent = null;
mainCategory.CategoryType = null;
mainCategory.ParentReference.EntityKey = new EntityKey("DbEntities.CategorySet", "Id", parentId); 
mainCategory.CategoryTypeReference.EntityKey = new EntityKey("DbEntities.CategoryTypeSet", "Id", typeId);

这篇关于MVC 2实体框架视图模型插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆