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

在无数据库的MVC教程中如何向列表添加模型实例

如何向无数据库MVC的ThingService列表添加模型实例?

嘿,我来帮你搞定这个问题!首先看你现有的ThingService代码,它通过懒加载初始化了一个内部的List<Thing>,但目前没有对外提供添加新实例的入口——所以我们要做的就是给这个服务类加一个公共的添加方法,让外部(比如控制器)能调用它来新增Thing实例。

步骤1:给ThingService添加AddThing方法

修改你的服务类,新增一个AddThing方法,同时可以加入一些基础的验证逻辑(比如防止添加空实例、自动生成ID等):

namespace Domain.Services {
    public class ThingService {
        private List<Thing> _things;
        private List<Thing> Things {
            get {
                if (this._things == null) {
                    this._things = new List<Thing>();
                    this._things.Add(new Thing() {
                        ID = 1,
                        Name = "The red thing",
                        Color = "Red",
                        Size = "Small",
                        Length = 55,
                        DateAvailable = DateTime.Parse("1/1/2018"),
                        IsActive = true
                    });
                    // Add more things
                }
                return this._things;
            }
        }

        // 新增公共方法:添加Thing实例
        public void AddThing(Thing newThing) {
            // 验证:不能添加空实例
            if (newThing == null) {
                throw new ArgumentNullException(nameof(newThing), "无法添加空的Thing对象");
            }

            // 可选:自动生成唯一ID(如果传入的ID为0)
            if (newThing.ID == 0) {
                newThing.ID = Things.Any() ? Things.Max(t => t.ID) + 1 : 1;
            }

            // 验证:避免重复ID(可选)
            if (Things.Any(t => t.ID == newThing.ID)) {
                throw new InvalidOperationException($"已存在ID为{newThing.ID}的Thing实例");
            }

            // 将新实例加入列表
            Things.Add(newThing);
        }
    }
}

步骤2:在外部调用AddThing方法

比如在你的MVC控制器里,你可以这样使用这个方法来添加新的Thing:

// 实例化ThingService
var thingService = new ThingService();

// 创建一个新的Thing实例
var newBlueThing = new Thing() {
    Name = "The blue thing",
    Color = "Blue",
    Size = "Medium",
    Length = 75,
    DateAvailable = DateTime.Now,
    IsActive = true
    // 这里可以不指定ID,让服务类自动生成
};

// 调用添加方法
thingService.AddThing(newBlueThing);

额外说明

  • 如果你不需要自动生成ID,也可以手动给newThing指定唯一的ID值,服务类里的ID验证逻辑会帮你检查是否重复。
  • 你还可以根据需求在AddThing方法里添加更多业务规则,比如检查Name是否为空、Length是否为正数等。

内容的提问来源于stack exchange,提问作者user1289397

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:30:08