开发者

Entity Framework 4.1 Code First: Advice on persisting data from external source?

开发者 https://www.devze.com 2023-03-08 07:19 出处:网络
Part of my project is to persist data from another source. In this case we have an SAP data source that we will need to pull data from. I need to take the data from SAP and map it to entities I have i

Part of my project is to persist data from another source. In this case we have an SAP data source that we will need to pull data from. I need to take the data from SAP and map it to entities I have in my application. Here is an example of an entity I have in my application:

    public class Project : BaseEntity
    {
        public string Name { get; set; }
        public string ProjectNumber { get; set; }
        public string Description { get; set; }

        public string CreatedBy { get; set; }
        public string ModifiedBy { get; set; }
        public string Currency { get; set; }

        #region Navigation Properties

        public virtual Address Address { get; set; }
        public virtual CompanyCode CompanyCode { get; set; }
        public virtual ICollection<Contact> TeamMembers { get; set; }

        #endregion
    }

As you can see, I have child objects that I map from SAP as well. I need some advice on the best way to insert and update my entities. I am struggling with knowing when to add (insert) entities to my context and when to attach (update) them, because SAP doesn't have knowledge of what my application may or may not have. I need to guard against duplicates, too. For example, s开发者_C百科hould I perform a lookup of each child entity in my parent entity to see if they exist before I apply them to the parent? Then, add / attach the entire parent object to the context or handle each entity separately while still maintaing their relationships?


Yes you must manually test everything to make correct decision what must be inserted, updated or deleted. Depending on the application you can use some more complex queries to reduce number of round trips to the database - for example you can use single query with Contains to load all TeamMembers needed for processed Project or you can load Project with including all related data if you also need to test if project exists.

I did large synchronization application before and I end up with pre-loading all entities at the beginning with few queries and working completely in memory.

Don't forget to use DbSet's Local property or Find method to take advantage of already loaded entities.

You can also use some custom stored procedures to improve performance of this operation.

0

精彩评论

暂无评论...
验证码 换一张
取 消