{"id":2414,"date":"2012-08-15T07:25:53","date_gmt":"2012-08-15T07:25:53","guid":{"rendered":"https:\/\/blogs.msdn.microsoft.com\/webdev\/2012\/08\/15\/using-dynamic-data-with-entity-framework-dbcontext\/"},"modified":"2012-08-15T07:25:53","modified_gmt":"2012-08-15T07:25:53","slug":"using-dynamic-data-with-entity-framework-dbcontext","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/dotnet\/using-dynamic-data-with-entity-framework-dbcontext\/","title":{"rendered":"Using Dynamic Data with Entity Framework DbContext"},"content":{"rendered":"<p>In Visual Studio 2012, if you create a ADO.NET Data Model then the generated Context class derives from a type called <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.data.entity.dbcontext(v=VS.103).aspx\" target=\"_blank\" rel=\"noopener\">DbContext<\/a> instead of ObjectContext. DbContext is also used when you are using <a href=\"http:\/\/msdn.microsoft.com\/en-us\/data\/ef.aspx\" target=\"_blank\" rel=\"noopener\">EntityFramework<\/a> Code First<\/p>\n<p>This post outlines the changes you have to do to your Dynamicdata project template if you want your context to derive from DbContext<\/p>\n<h3>1. Change Global.asax to get the ObjectContext<\/h3>\n<div class=\"csharpcode\">\n<div class=\"csharpcode\">\n<pre class=\"alt\"> DefaultModel.RegisterContext(() =&gt;<\/pre>\n<pre>            {<\/pre>\n<pre class=\"alt\">                <span class=\"kwrd\">return<\/span> ((IObjectContextAdapter)<span class=\"kwrd\">new<\/span> YourContextType()).ObjectContext;<\/pre>\n<pre>            }, <span class=\"kwrd\">new<\/span> ContextConfiguration() { ScaffoldAllTables = <span class=\"kwrd\">true<\/span> });<\/pre>\n<\/p><\/div>\n<\/p><\/div>\n<h3>2. Change ManyToMany.ascx.cs in the Dynamicdata\\Fieldtemplates folder<\/h3>\n<div class=\"csharpcode\">\n<pre class=\"alt\"><span class=\"kwrd\">protected<\/span> <span class=\"kwrd\">override<\/span> <span class=\"kwrd\">void<\/span> OnDataBinding(EventArgs e)<\/pre>\n<pre>        {<\/pre>\n<pre class=\"alt\">            <span class=\"kwrd\">base<\/span>.OnDataBinding(e);<\/pre>\n<pre>&#160;<\/pre>\n<pre class=\"alt\">            <span class=\"kwrd\">object<\/span> entity;<\/pre>\n<pre>            ICustomTypeDescriptor rowDescriptor = Row <span class=\"kwrd\">as<\/span> ICustomTypeDescriptor;<\/pre>\n<pre class=\"alt\">            <span class=\"kwrd\">if<\/span> (rowDescriptor != <span class=\"kwrd\">null<\/span>)<\/pre>\n<pre>            {<\/pre>\n<pre class=\"alt\">                <span class=\"rem\">\/\/ Get the real entity from the wrapper<\/span><\/pre>\n<pre>                entity = rowDescriptor.GetPropertyOwner(<span class=\"kwrd\">null<\/span>);<\/pre>\n<pre class=\"alt\">            }<\/pre>\n<pre>            <span class=\"kwrd\">else<\/span><\/pre>\n<pre class=\"alt\">            {<\/pre>\n<pre>                entity = Row;<\/pre>\n<pre class=\"alt\">            }<\/pre>\n<pre>&#160;<\/pre>\n<pre class=\"alt\">            <span class=\"rem\">\/\/ Get the collection and make sure it's loaded<\/span><\/pre>\n<pre>            var entityCollection = Column.EntityTypeProperty.GetValue(entity, <span class=\"kwrd\">null<\/span>);<\/pre>\n<pre class=\"alt\">            var realEntityCollection = entityCollection <span class=\"kwrd\">as<\/span> RelatedEnd;<\/pre>\n<pre>            <span class=\"kwrd\">if<\/span> (realEntityCollection != <span class=\"kwrd\">null<\/span> &amp;&amp; !realEntityCollection.IsLoaded)<\/pre>\n<pre class=\"alt\">            {<\/pre>\n<pre>                realEntityCollection.Load();<\/pre>\n<pre class=\"alt\">            }<\/pre>\n<pre>&#160;<\/pre>\n<pre class=\"alt\">&#160;<\/pre>\n<pre>            <span class=\"rem\">\/\/ Bind the repeater to the list of children entities<\/span><\/pre>\n<pre class=\"alt\">            Repeater1.DataSource = entityCollection;<\/pre>\n<pre>            Repeater1.DataBind();<\/pre>\n<pre class=\"alt\">        }<\/pre>\n<pre>&#160;<\/pre>\n<pre class=\"alt\">        <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">override<\/span> Control DataControl<\/pre>\n<pre>        {<\/pre>\n<pre class=\"alt\">            get<\/pre>\n<pre>            {<\/pre>\n<pre class=\"alt\">                <span class=\"kwrd\">return<\/span> Repeater1;<\/pre>\n<pre>            }<\/pre>\n<pre class=\"alt\">        }<\/pre>\n<\/div>\n<p><strong><font face=\"Courier New\"><\/font><\/strong><\/p>\n<h3>3. Change ManyToMany_Edit.ascx.cs in the Dynamicdata\\Fieldtemplates folder<\/h3>\n<div class=\"csharpcode\">\n<pre class=\"alt\"><span class=\"kwrd\">protected<\/span> ObjectContext ObjectContext { get; set; }<\/pre>\n<pre>&#160;<\/pre>\n<pre class=\"alt\">        <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">void<\/span> Page_Load(<span class=\"kwrd\">object<\/span> sender, EventArgs e)<\/pre>\n<pre>        {<\/pre>\n<pre class=\"alt\">            <span class=\"rem\">\/\/ Register for the DataSource's updating event<\/span><\/pre>\n<pre>            EntityDataSource ds = (EntityDataSource)<span class=\"kwrd\">this<\/span>.FindDataSourceControl();<\/pre>\n<pre class=\"alt\">&#160;<\/pre>\n<pre>            ds.ContextCreated += (_, ctxCreatedEnventArgs) =&gt; ObjectContext = ctxCreatedEnventArgs.Context;<\/pre>\n<pre class=\"alt\">&#160;<\/pre>\n<pre>            <span class=\"rem\">\/\/ This field template is used both for Editing and Inserting<\/span><\/pre>\n<pre class=\"alt\">            ds.Updating += <span class=\"kwrd\">new<\/span> EventHandler&lt;EntityDataSourceChangingEventArgs&gt;(DataSource_UpdatingOrInserting);<\/pre>\n<pre>            ds.Inserting += <span class=\"kwrd\">new<\/span> EventHandler&lt;EntityDataSourceChangingEventArgs&gt;(DataSource_UpdatingOrInserting);<\/pre>\n<pre class=\"alt\">        }<\/pre>\n<pre>&#160;<\/pre>\n<pre class=\"alt\">        <span class=\"kwrd\">void<\/span> DataSource_UpdatingOrInserting(<span class=\"kwrd\">object<\/span> sender, EntityDataSourceChangingEventArgs e)<\/pre>\n<pre>        {<\/pre>\n<pre class=\"alt\">            MetaTable childTable = ChildrenColumn.ChildTable;<\/pre>\n<pre>&#160;<\/pre>\n<pre class=\"alt\">            <span class=\"rem\">\/\/ Comments assume employee\/territory for illustration, but the code is generic<\/span><\/pre>\n<pre>            <span class=\"kwrd\">if<\/span> (Mode == DataBoundControlMode.Edit)<\/pre>\n<pre class=\"alt\">            {<\/pre>\n<pre>                ObjectContext.LoadProperty(e.Entity, Column.Name);<\/pre>\n<pre class=\"alt\">            }<\/pre>\n<pre>&#160;<\/pre>\n<pre class=\"alt\">            <span class=\"rem\">\/\/ Get the collection and make sure it's loaded<\/span><\/pre>\n<pre>            dynamic entityCollection = Column.EntityTypeProperty.GetValue(e.Entity, <span class=\"kwrd\">null<\/span>);<\/pre>\n<pre class=\"alt\">&#160;<\/pre>\n<pre>            <span class=\"rem\">\/\/ Go through all the territories (not just those for this employee)<\/span><\/pre>\n<pre class=\"alt\">            <span class=\"kwrd\">foreach<\/span> (dynamic childEntity <span class=\"kwrd\">in<\/span> childTable.GetQuery(e.Context))<\/pre>\n<pre>            {<\/pre>\n<pre class=\"alt\">&#160;<\/pre>\n<pre>                <span class=\"rem\">\/\/ Check if the employee currently has this territory<\/span><\/pre>\n<pre class=\"alt\">                var isCurrentlyInList = ListContainsEntity(childTable, entityCollection, childEntity);<\/pre>\n<pre>&#160;<\/pre>\n<pre class=\"alt\">                <span class=\"rem\">\/\/ Find the checkbox for this territory, which gives us the new state<\/span><\/pre>\n<pre>                <span class=\"kwrd\">string<\/span> pkString = childTable.GetPrimaryKeyString(childEntity);<\/pre>\n<pre class=\"alt\">                ListItem listItem = CheckBoxList1.Items.FindByValue(pkString);<\/pre>\n<pre>                <span class=\"kwrd\">if<\/span> (listItem == <span class=\"kwrd\">null<\/span>)<\/pre>\n<pre class=\"alt\">                    <span class=\"kwrd\">continue<\/span>;<\/pre>\n<pre>&#160;<\/pre>\n<pre class=\"alt\">                <span class=\"rem\">\/\/ If the states differs, make the appropriate add\/remove change<\/span><\/pre>\n<pre>                <span class=\"kwrd\">if<\/span> (listItem.Selected)<\/pre>\n<pre class=\"alt\">                {<\/pre>\n<pre>                    <span class=\"kwrd\">if<\/span> (!isCurrentlyInList)<\/pre>\n<pre class=\"alt\">                        entityCollection.Add(childEntity);<\/pre>\n<pre>                }<\/pre>\n<pre class=\"alt\">                <span class=\"kwrd\">else<\/span><\/pre>\n<pre>                {<\/pre>\n<pre class=\"alt\">                    <span class=\"kwrd\">if<\/span> (isCurrentlyInList)<\/pre>\n<pre>                        entityCollection.Remove(childEntity);<\/pre>\n<pre class=\"alt\">                }<\/pre>\n<pre>            }<\/pre>\n<pre class=\"alt\">        }<\/pre>\n<pre>&#160;<\/pre>\n<pre class=\"alt\">        <span class=\"kwrd\">private<\/span> <span class=\"kwrd\">static<\/span> <span class=\"kwrd\">bool<\/span> ListContainsEntity(MetaTable table, IEnumerable&lt;<span class=\"kwrd\">object<\/span>&gt; list, <span class=\"kwrd\">object<\/span> entity)<\/pre>\n<pre>        {<\/pre>\n<pre class=\"alt\">            <span class=\"kwrd\">return<\/span> list.Any(e =&gt; AreEntitiesEqual(table, e, entity));<\/pre>\n<pre>        }<\/pre>\n<pre class=\"alt\">&#160;<\/pre>\n<pre>        <span class=\"kwrd\">private<\/span> <span class=\"kwrd\">static<\/span> <span class=\"kwrd\">bool<\/span> AreEntitiesEqual(MetaTable table, <span class=\"kwrd\">object<\/span> entity1, <span class=\"kwrd\">object<\/span> entity2)<\/pre>\n<pre class=\"alt\">        {<\/pre>\n<pre>            <span class=\"kwrd\">return<\/span> Enumerable.SequenceEqual(table.GetPrimaryKeyValues(entity1), table.GetPrimaryKeyValues(entity2));<\/pre>\n<pre class=\"alt\">        }<\/pre>\n<pre>&#160;<\/pre>\n<pre class=\"alt\">        <span class=\"kwrd\">protected<\/span> <span class=\"kwrd\">void<\/span> CheckBoxList1_DataBound(<span class=\"kwrd\">object<\/span> sender, EventArgs e)<\/pre>\n<pre>        {<\/pre>\n<pre class=\"alt\">            MetaTable childTable = ChildrenColumn.ChildTable;<\/pre>\n<pre>&#160;<\/pre>\n<pre class=\"alt\">            <span class=\"rem\">\/\/ Comments assume employee\/territory for illustration, but the code is generic<\/span><\/pre>\n<pre>&#160;<\/pre>\n<pre class=\"alt\">            IEnumerable&lt;<span class=\"kwrd\">object<\/span>&gt; entityCollection = <span class=\"kwrd\">null<\/span>;<\/pre>\n<pre>&#160;<\/pre>\n<pre class=\"alt\">            <span class=\"kwrd\">if<\/span> (Mode == DataBoundControlMode.Edit)<\/pre>\n<pre>            {<\/pre>\n<pre class=\"alt\">                <span class=\"kwrd\">object<\/span> entity;<\/pre>\n<pre>                ICustomTypeDescriptor rowDescriptor = Row <span class=\"kwrd\">as<\/span> ICustomTypeDescriptor;<\/pre>\n<pre class=\"alt\">                <span class=\"kwrd\">if<\/span> (rowDescriptor != <span class=\"kwrd\">null<\/span>)<\/pre>\n<pre>                {<\/pre>\n<pre class=\"alt\">                    <span class=\"rem\">\/\/ Get the real entity from the wrapper<\/span><\/pre>\n<pre>                    entity = rowDescriptor.GetPropertyOwner(<span class=\"kwrd\">null<\/span>);<\/pre>\n<pre class=\"alt\">                }<\/pre>\n<pre>                <span class=\"kwrd\">else<\/span><\/pre>\n<pre class=\"alt\">                {<\/pre>\n<pre>                    entity = Row;<\/pre>\n<pre class=\"alt\">                }<\/pre>\n<pre>&#160;<\/pre>\n<pre class=\"alt\">                <span class=\"rem\">\/\/ Get the collection of territories for this employee and make sure it's loaded<\/span><\/pre>\n<pre>                entityCollection = (IEnumerable&lt;<span class=\"kwrd\">object<\/span>&gt;)Column.EntityTypeProperty.GetValue(entity, <span class=\"kwrd\">null<\/span>);<\/pre>\n<pre class=\"alt\">                var realEntityCollection = entityCollection <span class=\"kwrd\">as<\/span> RelatedEnd;<\/pre>\n<pre>                <span class=\"kwrd\">if<\/span> (realEntityCollection != <span class=\"kwrd\">null<\/span> &amp;&amp; !realEntityCollection.IsLoaded)<\/pre>\n<pre class=\"alt\">                {<\/pre>\n<pre>                    realEntityCollection.Load();<\/pre>\n<pre class=\"alt\">                }<\/pre>\n<pre>            }<\/pre>\n<pre class=\"alt\">&#160;<\/pre>\n<pre>            <span class=\"rem\">\/\/ Go through all the territories (not just those for this employee)<\/span><\/pre>\n<pre class=\"alt\">            <span class=\"kwrd\">foreach<\/span> (<span class=\"kwrd\">object<\/span> childEntity <span class=\"kwrd\">in<\/span> childTable.GetQuery(ObjectContext))<\/pre>\n<pre>            {<\/pre>\n<pre class=\"alt\">                <span class=\"rem\">\/\/ Create a checkbox for it<\/span><\/pre>\n<pre>                ListItem listItem = <span class=\"kwrd\">new<\/span> ListItem(<\/pre>\n<pre class=\"alt\">                    childTable.GetDisplayString(childEntity),<\/pre>\n<pre>                    childTable.GetPrimaryKeyString(childEntity));<\/pre>\n<pre class=\"alt\">&#160;<\/pre>\n<pre>                <span class=\"rem\">\/\/ Make it selected if the current employee has that territory<\/span><\/pre>\n<pre class=\"alt\">                <span class=\"kwrd\">if<\/span> (Mode == DataBoundControlMode.Edit)<\/pre>\n<pre>                {<\/pre>\n<pre class=\"alt\">                    listItem.Selected = ListContainsEntity(childTable, entityCollection, childEntity);<\/pre>\n<pre>                }<\/pre>\n<pre class=\"alt\">&#160;<\/pre>\n<pre>                CheckBoxList1.Items.Add(listItem);<\/pre>\n<pre class=\"alt\">            }<\/pre>\n<pre>        }<\/pre>\n<pre class=\"alt\">&#160;<\/pre>\n<pre>        <span class=\"kwrd\">public<\/span> <span class=\"kwrd\">override<\/span> Control DataControl<\/pre>\n<pre class=\"alt\">        {<\/pre>\n<pre>            get<\/pre>\n<pre class=\"alt\">            {<\/pre>\n<pre>                <span class=\"kwrd\">return<\/span> CheckBoxList1;<\/pre>\n<pre class=\"alt\">            }<\/pre>\n<pre>        }<\/pre>\n<\/div>\n<pre class=\"csharpcode\">&#160;<\/pre>\n<p>At this point you should be good to run your application and use DbContext or EntityFramework Code First with Dynamicdata templates<\/p>\n","protected":false},"excerpt":{"rendered":"<p>In Visual Studio 2012, if you create a ADO.NET Data Model then the generated Context class derives from a type called DbContext instead of ObjectContext. DbContext is also used when you are using EntityFramework Code First This post outlines the changes you have to do to your Dynamicdata project template if you want your context [&hellip;]<\/p>\n","protected":false},"author":408,"featured_media":58792,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[197],"tags":[],"class_list":["post-2414","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-aspnet"],"acf":[],"blog_post_summary":"<p>In Visual Studio 2012, if you create a ADO.NET Data Model then the generated Context class derives from a type called DbContext instead of ObjectContext. DbContext is also used when you are using EntityFramework Code First This post outlines the changes you have to do to your Dynamicdata project template if you want your context [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts\/2414","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/users\/408"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/comments?post=2414"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/posts\/2414\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/media\/58792"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/media?parent=2414"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/categories?post=2414"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/dotnet\/wp-json\/wp\/v2\/tags?post=2414"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}