Entity Framework 5 - Looking for Central Point to Execute Custom Code after Entity is Loaded from Database

前端 未结 2 596
盖世英雄少女心
盖世英雄少女心 2021-01-11 15:15

I am using Entity Framework 5 with Code First approach and using Fluent API for Entity configuration. My project has one particular Product Entity which gets half of its dat

2条回答
  •  遥遥无期
    2021-01-11 16:16

    Today I found an event in the Entity Framework that seems to be what I am looking for. ObjectContext.ObjectMaterialized Event. Apparently, DbContext implements IObjectContextAdapter which in-turn exposes the ObjectContext. From there I can subscribe to the ObjectMaterialized event.

    MSDN Reads: Occurs when a new entity object is created from data in the data source as part of a query or load operation.

    The following code demonstrates how I used the ObjectMaterialized event to solve my problem in which one of my preferences was to have a central point to place the WCF client access logic.

    // seperate assembly - does not use Domain.Repositories assembly
    namespace Domain.Models
    {
        // the data contract
        [DataContract]
        public class ProductInventoryState
        {
            [DataMember]
            public int StockStatus { get; set; }
    
            [DataMember]
            public IEnumerable SerialNumbers { get; set; }
    
            // etc....
        }
    
        // the entity
        public class Product
        {
            public Guid Key { get; set; }
            public string ProductCode { get; set; }
            public ProductInventoryState InventoryState { get; set; }
            // etc....
        }
    }
    
    // seperate assembly - uses Domain.Models assembly
    namespace Domain.Repositories
    {
        public class MainRepository : DbContext
        {
            public MainRepository()
            {
                ((IObjectContextAdapter)this).ObjectContext.ObjectMaterialized += ObjectContext_ObjectMaterialized;
            }
    
            protected void ObjectContext_ObjectMaterialized(object sender, ObjectMaterializedEventArgs e)
            {
                if (e.Entity == null)
                    return;
    
                if (e.Entity is Product)
                {
                    Product product = (Product)e.Entity;
    
                    // retrieve ProductInventoryState from 3rd party SOAP API
                    using (ThirdPartyInventorySystemClient client = new ThirdPartyInventorySystemClient())
                    {
                        // use ProductCode to retrieve the data contract
                        product.InventoryState = client.GetInventoryState(product.ProductCode);
                    }
                }
            }    
        }
    }
    

提交回复
热议问题