Click here to Skip to main content
15,895,084 members
Articles / Database Development / SQL Server

Reattaching Entity Graphs with the Entity Framework

Rate me:
Please Sign up or sign in to vote.
4.85/5 (39 votes)
10 Mar 2009CPOL15 min read 290.3K   1.7K   97  
A generic method for attaching detached object graphs to an Entity Framework context
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace CodeProject.Data.Entity
{
	[AttributeUsage(AttributeTargets.Class)]
	public sealed class AssociationEndBehaviorAttribute : Attribute
	{
		private static AssociationEndBehaviorAttribute defaultInstance = new AssociationEndBehaviorAttribute(String.Empty);

		public AssociationEndBehaviorAttribute(string endName)
		{
			this.EndName = endName;
		}

		public string EndName { get; private set; }
		public bool Owned { get; set; }

		public static AssociationEndBehaviorAttribute GetAttribute(PropertyInfo property)
		{
			return GetAttribute(property.DeclaringType, property.Name);
		}

		public static AssociationEndBehaviorAttribute GetAttribute(Type type, string endName)
		{
			// Loop over attributes and return matching one:
			foreach (AssociationEndBehaviorAttribute item in type.GetCustomAttributes(typeof(AssociationEndBehaviorAttribute), true))
				if (item.EndName == endName)
					return item;

			// If none found, return default one:
			return defaultInstance;
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect AREBIS
Belgium Belgium
Senior Software Architect and independent consultant.

Comments and Discussions