我有一个ViewModel
,其中包含将分配给Person
模型的人员数据,此ViewModel
还有一个Address
模型,此人有AddressId
模型1}}将该人与Address
。
我遇到的问题是,当我将ViewModel
映射到Person
并将EntityState
设置为Modified
时,只会显示Person
表格已更新和 新 Address
将被添加(如果已更改),而不是更新。
编辑:
型号:
public class Address : BaseModel
{
public int Id { get; set; }
[Required, Display(Name = "Line One"), MaxLength(128)]
[Index("IX_AddressCollectiveUniqueness", 1, IsUnique = true)]
public String LineOne { get; set; }
[Display(Name = "Line Two"), MaxLength(128)]
[Index("IX_AddressCollectiveUniqueness", 2, IsUnique = true)]
public String LineTwo { get; set; }
[Display(Name = "Line Three"), MaxLength(128)]
[Index("IX_AddressCollectiveUniqueness", 3, IsUnique = true)]
public String LineThree { get; set; }
[Required, MaxLength(32)]
[Index("IX_AddressCollectiveUniqueness", 4, IsUnique = true)]
public String Parish { get; set; }
[Required, MaxLength(16)]
[Index("IX_AddressCollectiveUniqueness", 5, IsUnique = true)]
public String Island { get; set; }
[Required, MaxLength(8)]
[Index("IX_AddressCollectiveUniqueness", 6, IsUnique = true)]
public String Postcode { get; set; }
public virtual ICollection<Person> People { get; set; }
}
public class Person : BaseModel
{
public int Id { get; set; }
public int? AddressId { get; set; }
[Required, Display(Name = "First Name"), MaxLength(32)]
public String FirstName { get; set; }
[Display(Name = "Middle Name"), MaxLength(64)]
public String MiddleName { get; set; }
[Required, Display(Name = "Last Name"), MaxLength(32)]
public String LastName { get; set; }
public virtual Address Address { get; set; }
}
ViewModel:
public class PersonManageVM
{
public int Id { get; set; }
public int? AddressId { get; set; }
public Address Address { get; set; }
[Required, MaxLength(4)]
public String Title { get; set; }
[Required, Display(Name = "First Name"), MaxLength(32)]
public String FirstName { get; set; }
[Display(Name = "Middle Name"), MaxLength(64)]
public String MiddleName { get; set; }
[Required, Display(Name = "Last Name"), MaxLength(32)]
public String LastName { get; set; }
}
控制器几乎与生成的更新方法完全相同,它只是设置了实体状态并保存。