【问题标题】:Create SQLite functions in Dbcontext (c#)在 Dbcontext 中创建 SQLite 函数 (c#)
【发布时间】:2022-12-17 18:50:00
【问题描述】:

我想在 EF-Core 中创建 sqlite 函数,特别是 newid(),并使用 DbContext 使用现有的与 SQLServer 兼容的 c# 代码来使用它们。

当我创建一个实体时,newid() 函数在 dbcontext.SaveChanges() 之后被 EF-Core 调用。

我能够使用新的 SQLiteConnection 创建函数

var connection = new SQLiteConnection(connectionString);
connection.CreateFunction("newid", () => Guid.NewGuid());

但是这些既不会持久化也不会被 DbContext 调用。

[DbFunction] 属性看起来很有前途,但我无法让它与 SQLite 数据库一起使用。

【问题讨论】:

    标签: c# sqlite entity-framework-core


    【解决方案1】:
    1. Add the [DbFunction] attribute to your function signature, specifying the function name and the schema name:
    [DbFunction("newid", "dbo")]
    public static Guid NewId()
    {
    return Guid.NewGuid();
    }
    
    2. In your DbContext, register the function using the modelBuilder:
    modelBuilder.HasDbFunction(typeof(MyFunctions).GetMethod(nameof(MyFunctions.NewId)));
    
    3. Use the function in your LINQ query, just like any other SQL function:
    var data = dbContext.MyEntities
    .Select(e => new {
    Id = e.Id,
    Guid = MyFunctions.NewId()
    });
    
    4. If you want the function to be called automatically by EF-Core when you call SaveChanges(), you can create a trigger in your SQLite database to call the function:
    CREATE TRIGGER newid_trigger
    AFTER INSERT ON MyEntities
    BEGIN
    UPDATE MyEntities
    SET Guid = newid()
    WHERE rowid = new.rowid;
    END;
    
    This approach allows you to use existing SQLServer code and consume SQLite functions in your DbContext, without having to create a new SQLiteConnection.
    

    【讨论】:

    • 存在一个误解,即现有代码是用 c# 编写的,但是是为 SQLServer 编写的(使用 ef-core)。我已经编辑了问题以使其更清楚。道歉。我无法让它工作,但也许可以在 Trigger 功能上探索更多
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-28
    • 2011-01-07
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多