如果我有模型:
public class User
{
public Account Account { get; set; }
public string SomeInfo { get; set; }
public Guid Id { get; set; }
}
public class Account
{
public Guid Id { get; set; }
public string Name { get; set; }
}
public class UserEntityTypeConfiguration : IEntityTypeConfiguration<User>
{
public virtual void Configure(EntityTypeBuilder<User> builder)
{
builder.HasKey(x => x.Id);
builder
.Property(t => t.Id)
.ValueGeneratedOnAdd();
}
}
当我在下面运行测试时,它显示该帐户已从用户中删除,但未从数据库中删除
[Test]
public async Task GivenAUser_WhenISetTheAccountToNull_ThenTheAccountIsRemovedFromTheDatabase()
{
Guid userId;
using (DbContext dbContext = GetDbContext())
{
UserRepository userRepository = new UserRepository(dbContext);
User newUser = new User
{
SomeInfo = "SomeInfo",
Account = new Account
{
Name = "Name"
}
};
await userRepository.SaveAsync(newUser);
userId = newUser.Id;
}
using (DbContext dbContext = GetDbContext())
{
UserRepository userRepository = new UserRepository(dbContext);
User user = await userRepository.GetAsync(userId);
user.Account = null;
await userRepository.SaveAsync(user);
}
User userDb;
int userAccountsCount;
using (DbContext dbContext = GetDbContext())
{
UserRepository userRepository = new UserRepository(dbContext);
userAccountsCount = await dbContext.Set<UserAccount>().CountAsync();
userDb = await userRepository.GetAsync(userId);
}
Assert.That(userDb.Account, Is.EqualTo(null)); // true
Assert.That(userAccountsCount, Is.EqualTo(0)); // false
}
我试图创建一个 UserEntityTypeConfiguration 来在可选字段上设置级联删除,但我似乎无法让它适用于可选字段。
public class UserEntityTypeConfiguration : IEntityTypeConfiguration<User>
{
public virtual void Configure(EntityTypeBuilder<User> builder)
{
builder.HasKey(x => x.Id);
builder
.Property(t => t.Id)
.ValueGeneratedOnAdd();
builder.HasOne(x => x.Account)
.WithOne()
.OnDelete(DeleteBehavior.Cascade);
}
}
任何人都可以帮忙吗?