在Dbcontext中创建SQLite函数(c#)

fsi0uk1n  于 2022-12-13  发布在  SQLite
关注(0)|答案(1)|浏览(226)

我想在EF-Core中创建sqlite函数,特别是newid(),并使用现有的与SQLServer兼容的c#代码(使用DbContext)来使用它们。
创建实体时,EF-Core会在dbcontext.SaveChanges()之后调用newid()函数。
我能够使用新的SQLiteConnection创建函数

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

但这些内容既不会持久化,也不会被DbContext调用。
[DbFunction]属性看起来很有前途,但我无法让它与SQLite数据库一起工作。

pgccezyw

pgccezyw1#

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.

相关问题