我的数据库中有一个地址表和一个状态表。当我在EF Core中的地址记录上调用更新时,我向现有的状态记录提供了一个ID。由于某种原因,查询正在将新记录插入到State表中,而不是查找现有记录。我的代码在下面。
这是调用数据访问的服务层代码:
public int UpsertContactInfo(ContactInfo contactInfo)
{
var mailingAddress = new AddressEntity() {
AddressLine1 = contactInfo.mailingAddressLine1,
AddressLine2 = contactInfo.mailingAddressLine2,
City = contactInfo.mailingCity,
ZipCode = contactInfo.mailingZip,
Id = contactInfo.mailingAddressId,
State = new StateEntity(){
Id = contactInfo.mailingStateId
}
};
_addressDataAccess.UpdateAddress(mailingAddress);
这是我的数据访问权限:
public int UpdateAddress(AddressEntity address)
{
_context.Addresses.Attach(address);
_context.SaveChanges();
return (int)address.Id;
}
ContactInfo:
using System;
namespace LandHawk.DataAccess.Entity
{
public class ContactInfoEntity
{
public int Id { get; set; }
public int PrimaryAddressId { get; set; }
public AddressEntity PrimaryAddress { get; set; }
public int MailingAddressId { get; set; }
public AddressEntity MailingAddress { get; set; }
}
}
状态:
using System;
namespace LandHawk.DataAccess.Entity
{
public class StateEntity
{
public int Id { get; set; }
public string Name { get; set; }
public string Abbreviation { get; set; }
}
}
不执行特殊映射。在我的databaseContext中:
public class DatabaseContext : DbContext
{
public DbSet<AddressEntity> Addresses { get; set; }
public DbSet<StateEntity> States { get; set; }
...
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<StateEntity>();
modelBuilder.Entity<AddressEntity>()
.Property(a => a.Id)
.ValueGeneratedOnAdd();
地址ID绝对设置为1,与数据库状态表中的现有记录匹配。但是,在进行呼叫时,会创建一个新的状态记录。