I'm trying to add user-defined functions with Entity Framework.
In DbContext
I've defined them as follows:
public IQueryable<GetProjectInspectionsFunctionResult> GetProjectInspections(int clientId, int projectId) => FromExpression(() => GetProjectInspections(clientId, projectId));
public IQueryable<GetProjectItemsFunctionResult> GetProjectItems(int clientId, int projectId) => FromExpression(() => GetProjectItems(clientId, projectId));
public IQueryable<GetProjectLopItemsFunctionResult> GetProjectLopItems(int clientId, int projectId) => FromExpression(() => GetProjectLopItems(clientId, projectId));
public IQueryable<GetProjectAttachmentsFunctionResult> GetProjectAttachments(int clientId, int projectId) => FromExpression(() => GetProjectAttachments(clientId, projectId));
modelBuilder.HasDbFunction(typeof(QAppDbContext).GetMethod(nameof(GetProjectInspections))).HasName("fn_GetProjectInspections");
modelBuilder.HasDbFunction(typeof(QAppDbContext).GetMethod(nameof(GetProjectItems))).HasName("fn_GetProjectItems");
modelBuilder.HasDbFunction(typeof(QAppDbContext).GetMethod(nameof(GetProjectLopItems))).HasName("fn_GetProjectLopItems");
modelBuilder.HasDbFunction(typeof(QAppDbContext).GetMethod(nameof(GetProjectAttachments))).HasName("fn_GetProjectAttachments");
I also have a configuration for each function:
public class GetProjectInspectionsConfiguration : IEntityTypeConfiguration<GetProjectInspectionsFunctionResult>
{
public void Configure(EntityTypeBuilder<GetProjectInspectionsFunctionResult> builder)
{
builder.HasNoKey();
}
}
I've also created an empty migration and defined each function:
migrationBuilder.Sql(
@"CREATE FUNCTION [dbo].[fn_GetProjectInspections]
(@clientId INT, @projectId INT)
RETURNS TABLE
AS
RETURN
(
WITH clients AS(...)
SELECT...
)"
)
And after I run the migration, an error occurs in DbContextSnapshot
because EF adds .ToTable(null)
for each function result type (eg. GetProjectInspectionsFunctionResult ).
Is there a way to overcome this situation? I think that I need to avoid any type of annotation (table, function, etc.)?
I managed to fix the issue by specifying the name explicitly for each function result entity (caused by methods overload):
modelBuilder.Entity<GetProjectInspectionsFunctionResult>((x) =>
{
x.HasNoKey();
x.ToTable(name: null);
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.