You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通用实体基类技术问询:接口设计思路与代码解析

Generic Entity Base Classes: Core Approach & Simplified Example

TL;DR

The key idea here is to consolidate all generic, non-entity-specific fields (like audit timestamps, unique IDs) into a shared interface, then have your actual business entities implement this interface instead of duplicating code across every entity.


From what I gathered, this pattern cuts down on repetitive code by centralizing common properties that every entity in your system needs—things like creation/modification dates, audit metadata, and unique identifiers. Instead of defining these fields in every single entity class, you bundle them into one or more interfaces, then have your entities inherit from those interfaces.

Here's a simplified breakdown with code examples to illustrate:

First, let's define the base modifiable entity interface (since IEntity inherits from it):

public interface IModifiableEntity
{
    DateTime? ModifiedDate { get; set; }
    string ModifiedBy { get; set; }
}

Then the main IEntity interface that extends it, adding creation-specific fields and an ID:

public interface IEntity : IModifiableEntity
{
    object Id { get; set; }
    DateTime CreatedDate { get; set; }
    string CreatedBy { get; set; }
}

Now, a concrete entity (like a Product) can implement this interface without repeating all those common fields:

public class Product : IEntity
{
    // Common fields from IEntity/IModifiableEntity
    public object Id { get; set; }
    public DateTime CreatedDate { get; set; }
    public string CreatedBy { get; set; }
    public DateTime? ModifiedDate { get; set; }
    public string ModifiedBy { get; set; }

    // Entity-specific fields
    public string ProductName { get; set; }
    public decimal Price { get; set; }
    public int StockQuantity { get; set; }
}

This way, every entity in your system gets those standard properties by implementing IEntity, and you only have to maintain those definitions in one place. It also makes it easier to add common behavior (like automated auditing logic) across all entities later on.


内容的提问来源于stack exchange,提问作者Uğur Cem Öztürk

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:21:27