EFCore 连表查询的WhereIf条件的使用示例

var query = from a in _DbContext.ProductInfo.AsNoTracking()
            join b in _DbContext.FinalAssemKeyPartBindings.AsNoTracking()
            on a.ProductInfoID equals b.ProductInfoID
            select new { a,b};
var list = query.Where(s => subOrderIds.Contains(s.a.SubManufacturingOrderID))
    .WhereIf(isFilterSerialCode, s => s.a.BikeSerialCode.Contains(search.SerialCode))
    .WhereIf(isFilterBikeFrameCode, s => s.b.KeyUniqueCode.Contains(search.BikeFrameCode))
    .Select(s => new {p = s.a,f = s.b}).ToList();
使用 Entity Framework Core(EF Core)进行数据库操作时,你不需要显式打开或关闭数据库连接。EF Core 会自动管理数据库连接的打开和关闭。 要使用 SQL 更新数据,你可以使用 EF Core 提供的 `ExecuteSqlRaw` 或 `ExecuteSqlInterpolated` 方法。这些方法允许你执行原始的 SQL 查询或命令。 下面是一个示例代码,展示了如何使用 EF Core 执行原始 SQL 更新数据: ```csharp using Microsoft.EntityFrameworkCore; using System; // 创建 DbContext 类 public class YourDbContext : DbContext { public YourDbContext(DbContextOptions<YourDbContext> options) : base(options) { } // DbSet 和其他属性... public DbSet<IPS_Invoice> IPS_Invoices { get; set; } } public class IPS_Invoice { public int IPS_ID { get; set; } public bool BLOCK { get; set; } public DateTime? BLOCKTIME { get; set; } } public class YourRepository { private readonly YourDbContext _dbContext; public YourRepository(YourDbContext dbContext) { _dbContext = dbContext; } public string UpdateBlockTime(IPS_Invoice model) { string message = ""; try { int affectedRows = _dbContext.Database.ExecuteSqlInterpolated($"UPDATE IPS_Invoices SET BLOCK = true, BLOCKTIME = {DateTime.Now} WHERE IPS_ID = {model.IPS_ID}"); if (affectedRows > 0) { message = "True"; } else { message = "No records updated"; } } catch (Exception e) { message = "False"; // 处理异常... } return message; } } ``` 在上述代码中,我们首先创建了一个继承自 `DbContext` 的 `YourDbContext` 类,并定义了需要操作的实体类 `IPS_Invoice`。然后,我们创建了一个名为 `YourRepository` 的仓储类,在该类中使用 `ExecuteSqlInterpolated` 方法执行原始的 SQL 更新操作。 在 `UpdateBlockTime` 方法中,我们使用插值字符串(interpolated string)来构建 SQL 命令,并将其传递给 `ExecuteSqlInterpolated` 方法进行执行。如果更新操作成功影响了一行或多行数据,返回的 `affectedRows` 将大于 0。 请根据你的实际情况修改代码,并确保在使用 EF Core 时按照最佳实践进行数据库操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值