Tag: Entity Framework

EntityType ‘Membership’ has no key defined. Define the key for this EntityType.

I have been using the Entity Framework since the very first version, and I’ve recently upgraded to version 5.2 on a rather large project of mine. Now, I’ve been using the ObjectContext all the time, since I have a lot of work invested in it, but I’m adding a new service to an existing app and for that I decided to use Code First and the DbContext instead. Well, it is not entire Code First, because I had the database in place and simply used the Reverse Engineer Code First option from the Entity Framework context menu (available when right-clicking the project in Solution Explorer in Visual Studio 2012).

I used my new and custom DbContext from a WCF data service, but when trying to access the service using Internet Explorer, I got the following error:

One or more validation errors were detected during model generation:
System.Data.Entity.Edm.EdmEntityType: : EntityType ‘Membership’ has no key defined. Define the key for this EntityType.
System.Data.Entity.Edm.EdmEntityType: : EntityType ‘Profile’ has no key defined. Define the key for this EntityType.
System.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet ‘Memberships’ is based on type ‘Membership’ that has no keys defined.
System.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet ‘Profiles’ is based on type ‘Profile’ that has no keys defined. ‘. See server logs for more details.

Now, as you may have guessed, I reverse engineered the tables used by the Universal Providers for the ASP.NET membership system. I need custom access to these tables, so I needed to get it working, and there are plenty of other developers who have come across these errors. However, none of the proposed solutions worked for me. The solution was rather simple, as I needed to decorate the UserId property with some attributes, as shown below. Yes, I like to use attributes and not the fluent Code First API…

public class Membership
     public System.Guid ApplicationId { get; set; }
     public System.Guid UserId { get; set; }
     public string Password { get; set; }
     public int PasswordFormat { get; set; }
     public string PasswordSalt { get; set; }
     public string Email { get; set; }
     public string PasswordQuestion { get; set; }
     public string PasswordAnswer { get; set; }
     public bool IsApproved { get; set; }
     public bool IsLockedOut { get; set; }
     public System.DateTime CreateDate { get; set; }
     public System.DateTime LastLoginDate { get; set; }
     public System.DateTime LastPasswordChangedDate { get; set; }
     public System.DateTime LastLockoutDate { get; set; }
     public int FailedPasswordAttemptCount { get; set; }
     public System.DateTime FailedPasswordAttemptWindowStart { get; set; }
     public int FailedPasswordAnswerAttemptCount { get; set; }
     public System.DateTime FailedPasswordAnswerAttemptWindowsStart { get; set; }
     public string Comment { get; set; }
     public virtual Application Application { get; set; }
     public virtual User User { get; set; }

public class Profile
     public System.Guid UserId { get; set; }
     public string PropertyNames { get; set; }
     public string PropertyValueStrings { get; set; }
     public byte[] PropertyValueBinary { get; set; }
     public System.DateTime LastUpdatedDate { get; set; }
     public virtual User User { get; set; }

It is needed to map the User navigation property with the User table by means of the UserId property. 🙂


Entity Framework model – uniqueidentifier primary keys

The Entity Framework has had a number of additions and fixes created over the years, and one I particularly like is the way to specify how to handle a GUID or rather a primary key in SQL Server of type uniqueidentifier. Previously you had to manually open the .edmx file in say Notepad and add the StoreGeneratedPattern attribute to your PK column and set the value to Identity. That in itself wasn’t too hard, but when you made changes to the model and saved it, those manual changes were overwritten. Now, the StoreGeneratedPattern attribute is part of the Visual Studio UI, or rather the Properties window in Visual Studio, making it easy to handle.

Let me point out, that the above scenario is really only applicable, if you do not have SQL Server handle the addition of a new row, by creating a new primary key value, by say using the newid or newsequentialid functions. If you have SQL Server handle the addition of a new row, you can set the StoreGeneratedPattern attribute to Identity, and in your partial entity class (say Country), you decorate the id column with the AllowEmptyStrings attribute and a value of false, like this:

public partial class Country
     internal class Country_Metadata
        [Required(AllowEmptyStrings = false)]
        public object Id { set; get; }
If your code adds the primary key, before you attempt to save it to the database, there’s little reason to set the StoreGeneratedPattern attribute.

ASP.NET Dynamic Data – Hide/show table or column

I am once again working with a helper project, which I need to have several people add data to a database, used with an upcoming release. Why use Dynamic Data? Well, it is simple and easy to get going, once you have your data model, for which I generally use the Entity Framework. Anyway, I had forgotten a few of the data annotations you can use with the metadata, including how to hide or show a table or column. However, it is really simple, once you look at the System.ComponentModel.DataAnnotations namespace.

The ScaffoldTable and ScaffoldColumn attributes can be used for this purpose, as shown here:

public partial class Culture
    internal class Culture_Metadata
        public bool Id { set; get; }

The table Culture is shown whereas the column Id isn’t shown, when using the scaffolding feature of Dynamic Data.

Silverlight Prism Application with authentication module

I’m currently redesigning an application to be Silverlight-based and implemented by using Prism. I’ve opted to use RIA Services to connect to the Entity Framework model, hosted by an ASP.NET Web application. However, to modularize it with Prism, I needed to remove the coupling between the ASP.NET Web app (Silverlight host) and the consumer, my Silverlight app, and I used Colin Blair’s idea, http://www.riaservicesblog.net/Blog/post/RIA-Services-Enterprise-Business-Application-Attempt-Part-One.aspx, as inspiration, not to mention copy much of the example code. 😉

Now, what I’m not so sure about, is whether to have the application services, including authentication (ASP.NET authentication), as a separate Prism module, or to have it as a shared assembly, tightly coupled/referenced from the Silverlight application.

Currently I am creating a Prism module for the horizontal application services, beginning with the authentication service, even if that takes a little more development. What do you think, should I opt for the shared assembly instead?

Could not load type ‘System.Data.Entity.Design.AspNet.EntityDesignerBuildProvider’.

I got this error when upgrading from RC1 of Visual Studio 2010 and the .NET Framework 4.0 RC1, to the RTM version of both. The fix is simple, very simple; simple add the outlined markup to your web.config file.

     <compilation debug="true" targetFramework="4.0">
         <add assembly="System.Security, Version=, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
         <add assembly="System.Data.Entity, Version=, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
         <add assembly="System.Data.Entity.Design, Version=, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
         <add extension=".edmx" type="System.Data.Entity.Design.AspNet.EntityDesignerBuildProvider" />

Many-To-Many Entity Modeling in Entity Framework

In my continued saga to create a new Web site based on ASP.NET 4 Dynamic Data and an Entity Data Model by using the Entity Framework 4, I needed to create or rather model a many-to-many relationships between 3 tables (3 pairs ;-)). While I have no problems doing that with an associated table in a SQL Server database, or any database, for that matter, I hadn’t done that in EF. However, I noticed that the Dynamic Data Web site, I had created, contained field templates for displaying and editing a Many-To-Many relationships. The problem was that while the database did work, I just could not model it using the Designer. Then I noticed that my association table contained three columns, the foreign keys for the two linked tables, but also a separate primary key. I generally create all my tables with an artificial primary key, and I had also done so in this case. Okay, I did a lot of other stuff first, before deciding to try and remove the artificial primary key column (of type uniqueidentifier) and create a composite primary key of the two “foreign key” columns. Then I updated the data model, but no luck. Hmm, okay, I then removed the 3 tables from the model, and subsequently updated the model from the database. In the update wizard, I added back the 3 tables and this time, 3 many-to-may relationships had been created. Great…

However, that wasn’t the best part; Dynamic Data automatically used the many-to-may field controls (ManyToMany.ascx and ManyToMany_Edit.ascx) to model the relationship in the UI. Particularly in edit view this was great, and it has saved me many hours of work. Mind you, a CheckBoxList control is sued, so if you have many rows in the linked table when editing an entity, it can become unwieldy to manage for an end-user.

An entry with the same key already exists.

I came across this error message the other day, working on a new ASP.NET 4 Dynamic Data Web site, and I was baffled as to what the problem was. I started troubleshooting and worked out that it happened with the Edit and Insert views. Okay, then I tried editing a row in all of my entities, just to see if any of them would work. I only had 8 tables at the time, so that wasn’t exactly a time consuming exercise. Much to my surprise, I was able to open one of the entities in the Edit view, but why so, when the others failed? I then looked at the number of columns exposed in the view and the entity that, for which the Edit view worked, only had a single column displayed. Then I tried hiding (ScaffoldColumn(False)) all columns but one in the metadata class for one of the partial entity classes, and then that worked. Now that worked, but it seemed a little silly, so I wasn’t going to let that beat me. After a while, I worked out that it happened when more than one column, displayed in the same type of UI control, or rather in this case a TextBox control, was used. So, I checked the associated Field Templates, and it was the validators attached to the TextBox control in the Text_Edit.ascx field control. Then it finally dawned upon me, it had to with the client ID’s of the controls. I looked at my web.config, in which I had this element:

masterPageFile="..." pageBaseType="..." clientIDMode="Static" />

Sure enough, removing the new ASP.NET 4.0 clientIDMode attribute and value fixed it. See Rick Strahl’s excellent article on this property, http://west-wind.com/weblog/posts/54760.aspx.

ASP.NET Dynamic Data 4 – UI Field Localization

In Dynamic Data for the .NET Framework 3.5 SP1, you manually had to localize the data fields at time of display, leading to some very hard-to-maintain code. This has all changed in Dynamic Data 4, or rather with the new System.ComponentModel.DataAnnotations.DisplayAttribute class, http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute_properties(VS.100).aspx, which can be used with Silverlight 3 and the .NET Framework 4. In particular, it can be used with your data model, LINQ to SQL or Entity Data Model (ADO.NET Entity Framework) to annotate your fields in a metadata class:

Visual Basic

Public Class Brand_Metadata

    Public Property Name As Object
End Class

Partial Public Class Brand
End Class

Continue reading “ASP.NET Dynamic Data 4 – UI Field Localization”