I have some models classes that inherit from a single abstract class, which in turn is deriving from BaseEntity
public abstract class Item: BaseEntity
When I try create an Entity Data Model on my context I get the following error:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Data.Entity.ModelConfiguration.ModelValidationException: One or more validation errors were detected during model generation:
DataLayer.EntityAspect: : EntityType 'EntityAspect' has no key defined. Define the key for this EntityType.
DataLayer.EntityKey: : EntityType 'EntityKey' has no key defined. Define the key for this EntityType.
DataLayer.MetadataStore: : EntityType 'MetadataStore' has no key defined. Define the key for this EntityType.
DataLayer.Validator: : EntityType 'Validator' has no key defined. Define the key for this EntityType.
DataLayer.DataType: : EntityType 'DataType' has no key defined. Define the key for this EntityType.
DataLayer.StructuralType: : EntityType 'StructuralType' has no key defined. Define the key for this EntityType.
DataLayer.ValidationError: : EntityType 'ValidationError' has no key defined. Define the key for this EntityType.
DataLayer.ValidationContext: : EntityType 'ValidationContext' has no key defined. Define the key for this EntityType.
DataLayer.StructuralProperty: : EntityType 'StructuralProperty' has no key defined. Define the key for this EntityType.
EntityAspects: EntityType: EntitySet 'EntityAspects' is based on type 'EntityAspect' that has no keys defined.
EntityKeys: EntityType: EntitySet 'EntityKeys' is based on type 'EntityKey' that has no keys defined.
MetadataStores: EntityType: EntitySet 'MetadataStores' is based on type 'MetadataStore' that has no keys defined.
Validators: EntityType: EntitySet 'Validators' is based on type 'Validator' that has no keys defined.
DataTypes: EntityType: EntitySet 'DataTypes' is based on type 'DataType' that has no keys defined.
StructuralTypes: EntityType: EntitySet 'StructuralTypes' is based on type 'StructuralType' that has no keys defined.
ValidationErrors: EntityType: EntitySet 'ValidationErrors' is based on type 'ValidationError' that has no keys defined.
ValidationContexts: EntityType: EntitySet 'ValidationContexts' is based on type 'ValidationContext' that has no keys defined.
StructuralProperties: EntityType: EntitySet 'StructuralProperties' is based on type 'StructuralProperty' that has no keys defined.
at System.Data.Entity.Core.Metadata.Edm.EdmModel.Validate()
at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.LazyInternalContext.get_ModelBeingInitialized()
at System.Data.Entity.Infrastructure.EdmxWriter.WriteEdmx(DbContext context, XmlWriter writer)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at Microsoft.DbContextPackage.Handlers.ViewContextHandler.ViewContext(MenuCommand menuCommand, Object context, Type systemContextType)
If I remove the BaseEntity inheritance and create an Entity Data Model, it completes successfully. What is BaseEntity doing to break my model?
The real world problem is that when I am attempting to return the metadata from the DataService.Metadata() call it hits this error too.
Any ideas how to get around this?
Thanks
Ended up using a "hack" whereby my server side entity models did not derive BaseEntity, but my client side entity models did. I accomplished this by using partial classes, and file links in VS
Related
[ForeignKey("Creator")]
public string CreatorID {get;set;}
public virtual ApplicationUser Creator {get;set;}
I have a model which I want to save the creator and modifier.
But there are errors during migration
TSRDTEST.Models.IdentityUserLogin: : EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType.
TSRDTEST.Models.IdentityUserRole: : EntityType 'IdentityUserRole' has no key defined. Define the key for this EntityType.
IdentityUserLogins: EntityType: EntitySet 'IdentityUserLogins' is based on type 'IdentityUserLogin' that has no keys defined.
IdentityUserRoles: EntityType: EntitySet 'IdentityUserRoles' is based on type 'IdentityUserRole' that has no keys defined.
I'm using built in login/logout/register template,with database column prefixs "AspNet", is there any way to fix that error without modify entire project project and preserve the columns with prefix AspNet, Thanks
Actually I didnt understand what you want to do. But the mapping between entities should be look like this.
public string CreatorID {get;set;}
[ForeignKey("CreatorID ")]
public virtual ApplicationUser Creator {get;set;}
Please tell me the meaning of this error?
{"One or more validation errors were detected during model
generation:\r\n\r\nMvcDemo.Models.Employee: : EntityType 'Employee'
has no key defined. Define the key for this EntityType.\r\nemp:
EntityType: EntitySet 'emp' is based on type 'Employee' that has no
keys defined.\r\n"}
I want to map the datatable object on entity framework model,
in DB, I have
dbo.testdata
-column
-AccountNumber(varchar(19),not null)
-KeyName(varchar(50),null)
-Value(varchar(500),not null)
How do I define in the model class to map all these objects, since EF require primary key, but all the object existing in the db now are not defined as primary Key?Also, I am using Scaffolding to the model.
public int Id {get; }{set;} ? should I be defined like this ?
public int AccountNumber{get; }{set;}
public string KeyName{get; }{set;}
public string Value{get; }{set;}
Modify your database to have primary key as you also have pointed out correctly that "EF require primary key". Check for these links for more info
Entity Framework: create entity and insert data in table without primary key and Entity Framework: table without primary key
I am trying to query my entity with a predicate on a DateTimeOffset column, but getting a 500 error response from the Breeze.WebApi. The error message is
Unable to perform operation: leon types:System.Nullable`1[System.DateTimeOffset], System.DateTime
The uri I see produced is something like
http://localhost:49800/api/Breeze Orders?$filter=LocalDateTime%20le%20datetime'2013-03-03T00%3A00%3A00.000Z'
What is working:
I can query on other DateTime, text columns
I can save new data into my 'LocalDateTime' field
The full error response from the query is:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Unable to perform operation: leon types:System.Nullable`1[System.DateTimeOffset], System.DateTime
</ExceptionMessage>
<ExceptionType>System.Exception</ExceptionType>
<StackTrace>
at Breeze.WebApi.ParseTreeVisitor.CoerceTypes(String operatorName, Expression& leftExpr, Expression& rightExpr) at Breeze.WebApi.ParseTreeVisitor.VisitBinary(ParseTreeNode node, String operatorName, Expression leftExpr, Expression rightExpr) at Breeze.WebApi.ParseTreeVisitor.VisitNode(ParseTreeNode node) at Breeze.WebApi.ParseTreeVisitor.Parse(Type rootType, ParseTreeNode node) at Breeze.WebApi.ExpressionTreeBuilder.Parse(Type rootType, String source) at Breeze.WebApi.ODataActionFilter.BuildFilterFunc(String filterQueryString, Type elementType) at Breeze.WebApi.ODataActionFilter.OnActionExecuted(HttpActionExecutedContext actionExecutedContext) at System.Web.Http.Filters.ActionFilterAttribute.CallOnActionExecuted(HttpActionContext actionContext, HttpResponseMessage response, Exception exception) at System.Web.Http.Filters.ActionFilterAttribute.<>c__DisplayClass2.<System.Web.Http.Filters.IActionFilter.ExecuteActionFilterAsync>b__0(HttpResponseMessage response) at System.Threading.Tasks.TaskHelpersExtensions.<>c__DisplayClass41`2.<Then>b__40(Task`1 t) at System.Threading.Tasks.TaskHelpersExtensions.ThenImpl[TTask,TOuterResult](TTask task, Func`2 continuation, CancellationToken cancellationToken, Boolean runSynchronously)
</StackTrace>
</Error>
.
EDIT
Getting there, but not quite. After installing Breeze 1.2.8 the client is now generating correctly typed uri e.g.
http://localhost:49800/api/Breeze/Orders?$filter=LocalDateTime%20ge%20datetimeoffset'2013-01-01T11%3A00%3A00.000Z'
In my case using setEntityTypeForResourceName to fix the entity type isnt needed. The above uri still gives me the error:
Unable to perform operation: leon types:System.Nullable`1[System.DateTimeOffset], System.DateTimeOffset
Changing my server side model from
public Nullable<System.DateTimeOffset> LocalDateTime { get; set; }
to
public System.DateTimeOffset LocalDateTime { get; set; }
allows my uri to work.
So can we please have a fix for nullable DateTimeOffset.
This is fixed in v 1.2.7. Please post back if you still see the error.
--- Further information ---
There have been several posts since 1.2.7 indicating that this error was still occuring. It turns out that the issue is NOT that breeze doesn't understand 'dataTimeOffsets'. It is that breeze is very forgiving of incorrect EntityType/Resource name mappings in queries except in the case of queries involving 'DateTimeOffsets'. This post is a bit long, so if you just need the fix, read the last paragraph.
The "Unable to perform operation: ... " error occurs when executing a query against a dateTimeOffset property when the resource name declared in the query ( the value in the 'from' clause) cannot be mapped to an existing entityType name (defined in metadata).
If breeze can find an entity type that maps to the resource name declared in the query, it uses the metadata for that entityType to validate the query and create an OData filter string. However, if it can't find a matching entity type, which is a perfectly acceptable condition because some 'resourceName's will not map to entities, it tries to infer the datatypes involved in any query clauses by looking at any constant parameters involved in the query and using their datatype. The problem is that a javascript date object can be mapped to either a .NET 'DateTime' or a 'DateTimeOffset' and Breeze can only pick one and in this case picks the 'wrong' one.
This kind of mismapping does not cause problems when data is returned from a query because breeze only uses the entity type of the query to validate and construct an appropriate OData filter string. Data returned from any query is inspected to determine the entityTypes of each item returned so the resourceName/entityType mapping is not needed. ( A single query may return multiple entity types because of the use of 'expand' or 'select' clauses.)
The root cause of the mapping issue involves the map of resource names to entity types that breeze keeps in each MetadataStore. This mapping is available via the MetadataStore.getEntityTypeNameForResourceName and MetadataStore.setEntityTypeForResourceName methods. When using Entity framework metadata, breeze assumes that Entity Framework 'EntitySet' names correspond to 'resourceNames'. This assumption is what is causing the problem. If you query a 'resourceName' that is different from one of your EntitySet names, Breeze does not know the corresponding 'entity Type' and falls back on inferring the datatypes used in the query, instead of using the 'entity Type' metadata.
There are two fairly simple fixes, either of which work.
1) Use the MetadataStore.setEntityTypeForResourceName method to map your resource names to your entity types. Note that you can have as many resource names as you like mapped to the same entity type.
2) Name your methods ( that correspond to resource names) to the names of the corresponding EntitySet defined in EF and not the name of the type that is returned. A common convention is that EntitySet names ( and hence resource names) are pluralized, whereas EntityType names are usually singular. i.e. 'Customers' is a resource name and 'Customer' is the EntityType
I'm trying to configure an MVC 4 application using EF 5 against the System.Web.Providers Membership DB. The ADO.NET Entity Data Model appears correct. The classes generated by the EF 5.x code generator look ok, but do not have a [Key] attribute. When I try to create a User Controller, I get the following error:
Microsoft Visual Studio
Unable to retrieve metadata for 'Citrius.Admin.User'. One or more validation errors were detected during model generation:
\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'Membership' has no key defined. Define the key for this EntityType.
\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'Profile' has no key defined. Define the key for this EntityType.
\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'Memberships' is based on type 'Membership' that has no keys defined.
\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'Profiles' is based on type 'Profile' that has no keys defined.
I thought I saw a walkthrough of this, using these versions, but cannot find it. I've tried to find a solution but all the examples are of previous versions.
Am I too far out on the bleeding edge?? Any help would be appreciated...
Why dont you assign the Key manually?
Go into each one and add [Key] above the field that should be the Key.
That should get rid of these errors.