我有2个使用Entity Framework 6配置的实体。 两个实体都具有身份标识,用于在插入时生成主键。
当我尝试添加新客户时,出现以下错误。
A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'Id'.
我的假设是我没有为一对一关系正确配置一个实体。
public class Customer : IdEntity
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Guid? BalanceId { get; set; }
public DateTime? Dob { get; set; }
public DateTime CreateDate { get; set; }
public CustomerBalance Balance { get; set; }
public Address Address { get; set; }
public virtual ICollection<Email> Emails { get; set; } = new List<Email>();
public virtual ICollection<Phone> Phones { get; set; } = new List<Phone>();
public virtual ICollection<Reward> Rewards { get; set; }
public ICollection<Call> Calls { get; set; }
}
这里是客户的映射
public class CustomerConfiguration : EntityTypeConfiguration<Customer>
{
public CustomerConfiguration()
{
ToTable(nameof(Customer));
HasKey(x => x.Id).Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasMany(x => x.Phones);
HasMany(x => x.Emails);
HasOptional(x => x.Balance);
HasRequired(x => x.Address).WithRequiredDependent(x=>x.Customer);
}
}
这里是地址实体
public class Address : IdEntity
{
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
public int CustomerId { get; set; }
public virtual Customer Customer { get; set; }
}
和映射
public class AddressConfiguration : EntityTypeConfiguration<Address>
{
public AddressConfiguration()
{
ToTable(nameof(Address));
HasKey(x => x.Id, e => e.IsClustered())
.Property(x => x.Id)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
}
这是我如何插入新客户的代码
var customer = new Customer
{
FirstName = request.FirstName,
LastName = request.LastName,
CreateDate = DateTime.Now,
Address = new Address()
};
if (!string.IsNullOrEmpty(request.Email))
customer.Emails.Add(new Email { EmailName = request.Email, IsPrimary = true });
if (!string.IsNullOrEmpty(request.Phone))
customer.Phones.Add(new Phone { Number = request.Phone, IsPrimary = true });
_repository.AddOneAsync(customer);
await _repository.Context.SaveChangesAsync();
保存更改时发生错误。 地址和客户是一对一的关系。
这是在SQL中配置表的方式
答案 0 :(得分:1)
EF6中的一对一关系必须使用相同的密钥。 EG Address.CustomerId必须是它的密钥。
要么允许客户在模型中拥有多个地址,要么将“ Address”的键更改为“ CustomerID”。