하나의 컨트롤러, 하나의보기 및 3 개의 C# 클래스에서 예제를 제공 할 수 있습니다. 이 코드를 사용하려면 Visual Studio에서 빈 MVC2 프로젝트를 만들고 Entity Framework dll 버전 4.1에 대한 참조를 추가하십시오. 이 파일들을 어디에 넣어야하는지에 관해 도움이 필요하면 나는 Steve Sanderson's MVC2 book을 추천한다.
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<User>" %>
<html>
<body>
<% using (Html.BeginForm())
{%>
Username: <%: Html.TextBoxFor(model => model.UserName) %><br />
Question: <%: Html.TextBoxFor(model => model.Question) %><br />
Location: <select name="categoryId">
<% foreach (var location in new Repository().GetLocations())
{%>
<option value="<%= location.ID %>">
<%= location.LocationName %></option>
<%} %>
<br />
</select>
<p>
<input type="submit" value="Create" />
</p>
<% } %>
</body>
</html>
홈 \ Index.aspx \
using System.Web.Mvc;
public class HomeController : Controller
{
Repository repo = new Repository();
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(User user, int categoryId)
{
user.Category = repo.GetLocation(categoryId);
repo.SaveUser(user);
return View();
}
}
조회수 :
public class User
{
public int ID { get; set; }
public string UserName { get; set; }
public string Question { get; set; }
public virtual Location Category { get; set; }
}
public class Location
{
public int ID { get; set; }
public string LocationName { get; set; }
}
저장소
using System.Data.Entity;
using System.Collections.Generic;
using System.Linq;
public class Repository : System.Data.Entity.DbContext
{
public DbSet<User> User { get; set; }
public DbSet<Location> Locations { get; set; }
public Repository()
{
this.Database.Connection.ConnectionString =
@"Server=.;Database=Test;Integrated Security=SSPI";
if (!this.Database.Exists())
{
this.Database.Create();
this.Locations.Add(new Location { LocationName = "Queensway" });
this.Locations.Add(new Location { LocationName = "Shepherds Bush" });
this.SaveChanges();
}
}
public IEnumerable<Location> GetLocations()
{
return this.Locations.Where(x => x.ID > -1);
}
public Location GetLocation(int id)
{
return this.Locations.First(x => x.ID == id);
}
public void SaveUser(User user)
{
this.User.Add(user);
this.SaveChanges();
}
}
컨트롤러 HomeContoller.cs을 \