c# - 通过业务逻辑初始化 Linq to Sql 对象

标签 c# .net linq linq-to-sql business-logic

我想扩展 Linq To Sql 生成的类,以在创建新对象(=行)时进行初始化。

我想在创建父行时向子表添加行。

我希望使用 Oncreated (部分)方法做这样的事情:

partial class Product {
    partial void OnCreated() {
        // Fill default rows for FK relations
        this.Columns.Add(new ProductColumn {
            Name = "Name", ColumnType = 1
        });
        this.Columns.Add(new ProductColumn {
            Name = "Producer", ColumnType = 2
        });
    }
}

每次构造函数都会调用 OnCreated。如果在调用 OnCreated 之后从数据库加载对象也是如此。而如果对象是从数据库加载的,则不想执行代码。

那么我可以在哪里向模型添加逻辑来初始化对象(-graph)?

最佳答案

Linq to SQL 生成的类中没有内置方法。当从数据库调用时,它们专门调用 OnLoaded,但当不是从数据库调用时,它们不会调用任何内容。我怀疑是因为没有办法确定......

我建议使用 Chris 建议的工厂方法。

关于c# - 通过业务逻辑初始化 Linq to Sql 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/689241/

相关文章:

c# - 使用 Microsoft.Jet.OLEDB.4.0 连接导入 Excel 表时出错

.net - WPF 路由命令是解决问题还是使问题变得更糟?

c# - WebAPI One Asp.Net (ASP5/vNext) 中的分页

c# - 对从 Linq2Sql 的 var 中获取 int 感到困惑

.net - 给出一个数字以返回 Enum 的近似值?

c# - 使用 C# 在 asp.net 中以 Word 格式转换货币格式的 int 值?

c# - IIS 7 配置数据库 : Setting the framework version and the managed pipeline mode programmatically

c# - 在 Windows 7 中捕获控制台退出 C#

.net - 如何使用 .net 在 Windows 资源管理器中预选文件?

c# - 如何在超时发生后处理 NotifyIcon (C#)