简体   繁体   中英

Automatically set added properties when retrieving database objects in C#

I am extending a large C# project that connects to SQL Server.

In the database I have an Inventory table which has a foreign key manufacturer_id from the Manufacturer table.

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.

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.

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;
    }
    ...
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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