Code First复制属性

时间:2014-07-30 12:43:45

标签: c# entity-framework ef-code-first

我有这两个模型:

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时,属性FirstnameLastnameEmailaddress会从UserModel复制到ContactPersonModel并覆盖我设定的价值观。我该如何防止这种行为?

0 个答案:

没有答案