经过几天的奋斗,我终于得到了这份工作.
我有一个简单的人员和部门数据库:
我可以使用强类型的ASP.NET MVC视图作为参考/导航属性!查看部门列表......
带有DropDownList的ASP.NET MVC http://img11.imageshack.us/img11/7619/dropdownlistdepartment.gif
我的人物/编辑视图的一部分:
<% using (Html.BeginForm()) {%>
<%= Html.Hidden("Id", Model.Id) %>
<fieldset>
<legend>Fields</legend>
<p>
<label for="Name">Name:</label>
<%= Html.TextBox("Name", Model.Name) %>
</p>
<p>
<label for="DepartmentId">Department:</label>
<%= Html.DropDownList("DepartmentId", new SelectList((IEnumerable)ViewData["Departments"], "Id", "Name"))%>
</p>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<% } %>
Run Code Online (Sandbox Code Playgroud)
我的Person控制器的一部分:
//
// GET: /Person/Edit/5
public ActionResult Edit(Guid id)
{
ViewData["Departments"] = ctx.Department;
Person model = (from Person p in ctx.Person
where p.Id == id
select p).FirstOrDefault();
return View(model);
}
//
// POST: …Run Code Online (Sandbox Code Playgroud) 我正在使用EF尝试使用ASP.NET更新实体.我正在创建一个实体,设置它的属性然后将其传递回具有ID的单独图层上的EF,以便可以应用更改.我这样做是因为我只存储实体的ID,当它绑定到UI控件时.
一切都适用于标准属性,但我无法更新产品(相关实体)的Category.ID.我已经尝试过EntityKey,EntityReference和其他一些但不保存类别ID.这就是我所拥有的:
Product product = new Product();
product.CategoryReference.EntityKey = new EntityKey("ShopEntities.Categories", "CategoryID", categoryId);
product.Name = txtName.Text.Trim();
... other properties
StockControlDAL.EditProduct(productId, product);
public static void EditProduct(int productId, Product product) {
using(var context = new ShopEntities()) {
var key = new EntityKey("ShopEntities.Products", "ProductID", productId);
context.Attach(new Product() { ProductID = productId, EntityKey = key });
context.AcceptAllChanges();
product.EntityKey = key;
product.ProductID = productId;
context.ApplyPropertyChanges("ShopEntities.Products", product);
context.SaveChanges();
}
}
Run Code Online (Sandbox Code Playgroud)
我真的想使用EF,但我似乎在使用ASP.NET时遇到了一些问题.