2015-12-08 100 views
0

我使用VS2015社区版MVC5之后从实体框架的所有数据恢复 - 我EF6如何更新模型

创建了一个简单的模型及其CRUD操作。模型:Person,Fields(Id,FirstName,LastName,DateofBirth ...)。

当我更新模型(添加两个引用字段与默认值)。

添加到人物模型的字段:(国籍_Id,城市_Id),他们每个人都是国籍和城市表格的外键。

当我返回到索引方法

// GET: 
public ActionResult Index() 
{ 
    List<Person> persons = db.Persons.ToList(); 
    return View(persons); 
} 


public class Person 
{ 
    public int Id { get; set; } 
    public string DocumentCode { get; set; } 
    public string Name1 { get; set; } 
    public string Name2 { get; set; } 
    public string Name3 { get; set; } 
    public string Name4 { get; set; } 
    public DateTime DateOfBirth { get; set; } 
    public Address Address { get; set; } 
} 

public class Address 
{ 
    public int Id { get; set; } 
    public string Name { get; set; } 
    public List<Person> persons { get; set; } 
} 

下面是一些控制器方法

// GET: People 
    public ActionResult Index() 
    { 
     List<Person> persons = db.Persons.ToList(); 
     return View(persons); 
    } 


    // GET: People/Create 
    public ActionResult Create() 
    { 
     ViewBag.Addresses = new SelectList(db.Adresses, "Id", "Name"); 
     return View(); 
    } 

    // POST: People/Create 
    [HttpPost] 
    [ValidateAntiForgeryToken] 
    public ActionResult Create([Bind(Include = "Id,DocumentCode,Name1,Name2,Name3,Name4,DateOfBirth,Address")] Person person) 
    { 
     if (ModelState.IsValid) 
     { 
      db.Persons.Add(person); 
      db.SaveChanges(); 
      return RedirectToAction("Index"); 
     } 

     return View(person); 
    } 

这里是一段代码中创建视图(应负责从视图中检索数据)

<div class="form-group"> 
     @Html.LabelFor(model => model.Address, ClinicDemo.App_Start.SystemTranslation.ADDRESS, htmlAttributes: new { @class = "control-label col-md-2" }) 
     <div class="col-md-10"> 
      @Html.DropDownList("Address_Id", (IEnumerable<SelectListItem>)ViewBag.Addresses, new { @class = "form-control" }) 
      @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" }) 
     </div> 
    </div> 

这是一段代码,应根据广告查看地址名称dress_id,它仍然是空的,即使在一些硬编码数据

<td> 
     @Html.DisplayFor(modelItem => item.Address.Name) 
    </td> 

人反对恢复所有数据,甚至没有当我从数据库中手动设置,当我添加新的人的所有数据都设置正确,除了那些字段中的新领域,

任何帮助?

+0

请显示新的Person类和代码,在其中创建一个新的Person。没有它就很难猜出有什么不对。 –

回答

0

默认值将不会填充旧数据,您需要自己对数据库进行更改。应该很简单:

update Person set FieldName = "defaultvalue" 
+0

这个问题也在新数据中。这是保存新记录时的错误'不能将值NULL插入列'Address_Id',表'aspnet-ClinicDemo-20151204092505.dbo.People';列不允许有空值。 INSERT失败。' –

+0

请发布您用于添加记录的完整代码。在上面的情况下,它看起来像你没有设置AddressId字段,它必须不为空。 – Woland