我有这两个模型:
UserModel
[Table("user")]
public class UserModel {
[Key]
[Column("emailaddress")]
public string Emailaddress { get; set; }
[Column("firstname")]
public string Firstname { get; set; }
[Column("lastname")]
public string Lastname { get; set; }
}
ContactPersonModel
[Table("contactperson")]
public class ContactPersonModel {
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
[Column("firstname")]
public string Firstname { get; set; }
[Column("lastname")]
public string Lastname { get; set; }
[Column("emailaddress")]
[EmailAddress]
[Index(IsUnique = true)]
[MaxLength(255)]
public string Emailaddress { get; set; }
[Column("phonenumber")]
[Phone]
public string Phonenumber { get; set; }
public virtual UserModel Creator { get; set; }
}
这是我用来在数据库中插入项目的方法:
public async Task<ContactPersonModel> AddContactPerson(ContactPersonModel model) {
dbmodel.ContactPerson.Add(model);
dbmodel.Entry(model.Creator).State = EntityState.Unchanged;
if (await dbmodel.SaveChangesAsync() == 0) {
Log.ErrorFormat("cannot add contactperson {0}", model.Emailaddress);
throw new Exception("cannot add contactperson");
} else {
await dbmodel.Entry(model).ReloadAsync();
return model;
}
}
当我调用方法AddContactPerson
时,属性Firstname
,Lastname
和Emailaddress
会从UserModel
复制到ContactPersonModel
并覆盖我设定的价值观。我该如何防止这种行为?