简体   繁体   English

在C#中检索数据库对象时自动设置添加的属性

[英]Automatically set added properties when retrieving database objects in C#

I am extending a large C# project that connects to SQL Server. 我正在扩展连接到SQL Server的大型C#项目。

In the database I have an Inventory table which has a foreign key manufacturer_id from the Manufacturer table. 在数据库中,我有一个库存表,该表具有来自制造商表的外键maker_id。

I have added some properties to the Inventory class from the Manufacturer table because the app must continue to send Inventory objects but now include Manufacturer information as well. 我已经从Manufacturer表中向Inventory类添加了一些属性,因为该应用必须继续发送Inventory对象,但现在也包括了Manufacturer信息。

public partial class Inventory
{
    public string ManufacturerName {get; set;}
}            

In my InventoryRepository I now call my SetManufacturerName method whenever I return Inventory objects and must remember to call it in any new methods. 现在,在我的InventoryRepository中,无论何时我返回Inventory对象,我都将调用SetManufacturerName方法,并且必须记住要在任何新方法中调用它。

Is there a way to call a method automatically whenever an Inventory object is retrieved from the database? 每当从数据库中检索库存对象时,是否可以自动调用方法?

I am unable to change anything in the database. 我无法更改数据库中的任何内容。

You can call your desired method in the constructor of the class. 您可以在类的构造函数中调用所需的方法。 It will ensure that whenever an instance of object is created your method is called 这将确保无论何时创建对象的实例,您的方法都将被调用

      public partial class Inventory
      {
         public Inventory() { YourMethodCall(); }
         public string ManufacturerName {get; set;}
      } 

You don't have to call anything upon object creation, just provide a non-trivial implementation of the property 您不必在创建对象时调用任何东西,只需提供该属性的非平凡实现即可

 public string ManufacturerName
 {
    get
    {
        // your code here,e.g.
        return this.Manufacturer.Name;
    }
    ...
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM