c# - EF Core 不加载已通过 SqlRaw 添加到 DB 的实体
问题描述
我使用EF Core
过SQLite DataBase Provider。当我尝试通过 SqlRaw 命令查找已添加到 DB 的实体时,该First()
方法返回 null,而我认为它不应该是。我想知道为什么?
但:
如果我
int
用作模型类的键,则没有问题。如果我通过添加实体
DbContext
,一切都会按我的预期工作。
测试类:
[Fact]
public void Test1()
{
var services = new ServiceCollection();
var connectionStringBuilder = new SqliteConnectionStringBuilder()
{
DataSource = ":memory:",
};
var connection = new SqliteConnection(connectionStringBuilder.ToString());
services.AddDbContext<MyDbContext>(options =>
options
.UseSqlite(connection));
var serviceProvider = services.BuildServiceProvider();
var context = serviceProvider.GetService<MyDbContext>();
context.Database.OpenConnection();
context.Database.EnsureCreated();
var id = Guid.NewGuid();
AddDevice(context, id);
Assert.NotEmpty(context.Devices); // OK
Assert.NotNull(context.Devices.First(x => x.Id == new DeviceId(id)); // Fail
}
private void AddDevice(MyDbContext context, Guid id)
{
string sqlInsert = $"INSERT INTO \"Devices\" (\"Id\") VALUES ('{id}')";
context.Database.ExecuteSqlRaw(sqlInsert);
}
模型类:
public class Device
{
public DeviceId Id { get; private set; }
private string _token;
private Device()
{
}
public Device(string token)
: this()
{
Id = new DeviceId(Guid.NewGuid());
_token = token;
}
}
public class DeviceId : IEquatable<DeviceId>
{
public Guid Value { get; }
public DeviceId(Guid guid)
{
this.Value = guid;
}
public bool Equals(DeviceId other)
{
return this.Value.Equals(other.Value);
}
}
配置类:
internal class DeviceConfiguration : IEntityTypeConfiguration<Device>
{
public void Configure(EntityTypeBuilder<Device> builder)
{
builder.ToTable("Devices");
builder.HasKey(x => x.Id);
builder.Property(x => x.Id)
.HasConversion(
v => v.Value,
v => new DeviceId(v));
builder.Property<string>("_token").HasColumnName("Token");
}
}
解决方案
推荐阅读
- angularjs - 超过 50,000 条记录在 angularjs 的下拉列表中加载 ng-repeat
- windows - 天蓝色管道“命令行”代理作业是否从上一个作业继承工作目录?
- flutter - 有没有办法连接到安卓设备的激光扫描仪?
- python - Matplotlib ValueError:具有多个元素的数组的真值不明确。使用 a.any() 或 a.all()
- python-3.x - Python '\r' 在同一行打印,但不会删除前面的文本
- google-chrome-extension - Chrome 扩展 newTab 和 amazon associates
- encryption - 如何将 30 位数字加密为 10 位数字?
- java - 在泛型类型中使用方法
- php - 在多对多上使用 LIKE 进行教义查询 - Symfony 4
- c++ - 如何遍历结构中的向量?