首页 > 解决方案 > EF Core 不加载已通过 SqlRaw 添加到 DB 的实体

问题描述

我使用EF CoreSQLite DataBase Provider。当我尝试通过 SqlRaw 命令查找已添加到 DB 的实体时,该First()方法返回 null,而我认为它不应该是。我想知道为什么?

但:

测试类:

    [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");
    }
}

标签: c#entity-frameworksqliteentity-framework-corein-memory-database

解决方案


推荐阅读