惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

J
Java Code Geeks
aimingoo的专栏
aimingoo的专栏
Martin Fowler
Martin Fowler
C
Check Point Blog
G
Google Developers Blog
V
Visual Studio Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Google DeepMind News
Google DeepMind News
人人都是产品经理
人人都是产品经理
有赞技术团队
有赞技术团队
MongoDB | Blog
MongoDB | Blog
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
大猫的无限游戏
大猫的无限游戏
D
Docker
Hugging Face - Blog
Hugging Face - Blog
The GitHub Blog
The GitHub Blog
博客园 - 三生石上(FineUI控件)
A
About on SuperTechFans
Recent Announcements
Recent Announcements
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
阮一峰的网络日志
阮一峰的网络日志
Stack Overflow Blog
Stack Overflow Blog
Vercel News
Vercel News

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Dynamic Column Updates in EF Core Without Hand-Rolling SQ...
scubaDEV · 2026-06-15 · via DEV Community
Cover image for Dynamic Column Updates in EF Core Without Hand-Rolling SQL Injection

scubaDEV

Sometimes you genuinely need the set of columns to update to be data, not code. An operator maps configuration fields to database columns, and you want to honor that mapping without redeploying every time it changes. The naive solution — build an UPDATE string from those column names — is also one of the easiest ways to hand-write a SQL injection vulnerability. This is how to get the flexibility without the hole.

We'll build it up in three layers: make it work, make it safe, then count the cost.

Layer 1: The dynamic update, the wrong way

The tempting version concatenates column names into SQL:

// DO NOT do this.
var sql = $"UPDATE products SET {columnName} = {value} WHERE id = {id}";

If columnName comes from configuration that an operator can edit, you've just made your schema writable by whoever controls that config. A value of name = 'x'; DROP TABLE products; -- is now your problem. Even "trusted" config is an injection surface the moment it flows into a SQL string.

Layer 2: The same feature with EF.Property

EF Core's ExecuteUpdateAsync lets you set a property by name without ever building SQL yourself. EF.Property<T> takes the property name as a string, and EF parameterizes the value and validates the property against the model:

await db.Products
    .Where(p => p.Id == id)
    .ExecuteUpdateAsync(setters => setters
        .SetProperty(p => EF.Property<float?>(p, columnName), value));

This is already a different security posture: the value is a parameter, not interpolated text, and EF will throw rather than emit SQL if columnName isn't a real mapped property. But "EF will throw" is a runtime backstop, not a policy. We want to reject bad names before they reach the database, fail closed, and control exactly which columns are writable.

Layer 3: Reflection as a whitelist

The guard is to validate every incoming column name against the entity's actual properties, using reflection, and to keep an explicit blacklist of fields that must never be touched dynamically:

private static readonly HashSet<string> Forbidden =
    new(StringComparer.Ordinal) { "Id", "CustomerId", "CreatedAt" };

private static readonly HashSet<string> Allowed =
    typeof(Product)
        .GetProperties(BindingFlags.Public | BindingFlags.Instance)
        .Select(p => p.Name)
        .Where(name => !Forbidden.Contains(name))
        .ToHashSet(StringComparer.Ordinal);

public async Task ApplyAsync(int id, IReadOnlyDictionary<string, float?> updates)
{
    foreach (var key in updates.Keys)
        if (!Allowed.Contains(key))
            throw new InvalidOperationException($"Column '{key}' is not updatable.");

    await using var tx = await db.Database.BeginTransactionAsync();
    var query = db.Products.Where(p => p.Id == id);

    foreach (var (name, value) in updates)
        await query.ExecuteUpdateAsync(s =>
            s.SetProperty(p => EF.Property<float?>(p, name), value));

    await tx.CommitAsync();
}

The important properties of this design:

  • Whitelist, not blacklist, as the primary control. The set of allowed names is derived from the type itself, so it can't drift out of sync with the schema. The blacklist only subtracts the sensitive few.
  • Fail closed. An unknown column raises before any database call, and the transaction means a bad item rolls everything back rather than half-applying.
  • No SQL is ever constructed from input. The column name only ever indexes into a validated set and is handed to EF as a model property reference.

The cost, stated honestly

This isn't free. You pay reflection and a dictionary lookup per field, and one ExecuteUpdateAsync per column rather than one combined statement. For a handful of configurable fields on a record, that's nothing. For a hot path updating dozens of columns across millions of rows, you'd cache the allowed set (as above, it's static) and consider batching. Measure before you optimize, but know the trade is there.

The principle to carry off

Dynamic behavior driven by config is fine. Dynamic SQL text built from config is the danger. The fix isn't to ban the feature — it's to make sure every externally-influenced identifier is validated against a server-side whitelist that the user can't expand, and to let the ORM parameterize values so you never assemble a query string by hand. Reflection over your own type is the cleanest source for that whitelist, because the schema is the source of truth.