[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;}
Related
I'm using Entity Framework to map some tables, but I can't do this unless I declare some column as the primary key.
The problem here is that my table in my database don't have a primary key and has millions of rows. I don't have permission to create a new Id column.
[Table("MYTABLE")]
public class myTable
{
[Column("NUMX")]
public virtual string NumX { get; set; }
[Column("NAME")]
public virtual string Name { get; set; }
[Column("AGE")]
public virtual int AGE { get; set; }
}
Obs: If I add the [Key] attribute to some column like Age, it works, but returns the wrong data.
Is there some way to omit the primary key?
I Figured out the problem.
Composite Keys works for me:
eg:
In my Context I defined some keys, not only one, but three keys:
public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
**//Here is the secret**
modelBuilder.Entity<MyModel>().HasKey(x => new { x.NumX, x.Name,x.Age});
}
}
Entity Framework requires a primary key unlike SQL.
EF use the primary key to uniquely identify rows (for example when you use .Find() or to perform update operations).
Infact not having a primary key remember a SQL VIEW, where you can only read data.
If any of the columns uniquely identify a certain row set it as a primary key (it can't be NULL) also if in Sql it isn't a key.
Otherwise if the combination of the columns are uniquely, create a composite key with these columns.
Remember that you should have a primary key in the 99% of cases, when you don't have a primary key you should stop and think if it make sense.
I have a three layer project(DAL, Domain, MVC). I need to bound AuthorEntity from the DAL with ApplicationUser, which is in the MVC project.
They have a different context(EfContext, ApplicationDbContext).
First, I created a UserEntity and tried to implement IUser, which has string field Id (sting Id{get;}), I got an error:
"EntityType 'UserEntity' has no key defined.Define the key for this
EntityType"
I add attributes:
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
It's not working. How to do this?
Primary Key property must be readable and writable.
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public string Id{get;set;}
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
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
Motivation : My EF4.1 DbContext is saving Entities in the wrong order
Reason : Lack of navigation properties on my models
How I want to fix it :
I want to set up foreign key relationships in my DbContext. The catch is that my entity objects have no navigation properties (I'm using it to populate a web service and then firing DTO objects over to my application).
The classes below would be an example. In MinorClass, I want to configure my context so that it knows MajorClassID is a foreign key. The articles I've been finding on the internet on how to explicitly define Foreign Keys involve using navigational properties, which my objects dont have.
Is there a way to map this relationship?
public class MinorClass
{
public Guid ID {get;set:}
public Guid MajorClassID {get;set;} // foreign key
public string Name {get;set;}
}
public class MajorClass
{
public Guid ID {get;set;}
public string Name {get;set;}
}
Navigation property is primary construct whereas foreign key is helper (imho wrong helper). EF recognizes ordering of DB commands by relationships which are defined by navigation properties. You cannot define relation just by foreign key. You need navigation property on at least one side of the relation.