I have an error:
One or more validation errors were detected during model generation:
\tSystem.Data.Entity.Edm.EdmEntityType: : EntityType 'DynamicMenu' has no key defined. Define the key for this EntityType.
\tSystem.Data.Entity.Edm.EdmEntitySet: EntityType: EntitySet 'ambt_Dynamic_Menu' is based on type 'DynamicMenu' that has no keys defined.
in helper class which code is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Data.Models;
using Data;
namespace Ambermoda.Web
{
public class MenuHelper
{
public static List<DynamicMenu> GetMenu()
{
DataContext db = new DataContext();
List<DynamicMenu> list = db.ambt_Dynamic_Menu.ToList();
return list;
}
}
}
so I have no idea how can I solve it. I checked everything what (in my opinion) can generate this error, but with any results.
I sam similar posts but any of them doesn't solve my problem.
If anybody have some idea, pleas write it :)
Thanks!
Some more code
DynamicMenu.cs
[Table("abmt_Dynamic_Menu")]
public class DynamicMenu
{
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int dmn_id { get; set; }
public string dmn_code { get; set; }
public string dnm_parent_code { get; set; }
public string dnm_title { get; set; }
public string dnm_title_en { get; set; }
public int dnm_order { get; set; }
}
DataContext.cs
public class DataContext : DbContext
{
public DataContext() { }
public DbSet<DynamicMenu> ambt_Dynamic_Menu { get; set; }
}
Connection string:
<add name="DataContext" providerName="System.Data.SqlClient" connectionString="Data Source=Mikasasa-lap\Mikasasa;Database=Ambermoda;Integrated Security=True;Pooling=False;"/>
According to source code you provided, you're working with the Code First approach.
CF assumes that class should have property named "Id" by the naming convention, and this property will be treated as primary key.
Otherwise, you should manually declare primary key via attribute [Key] or using fluent API (see EntityTypeConfiguration.HasKey method).
You need to inform what field is your database Primary Key. Use the attribute Key to do this:
[Table("abmt_Dynamic_Menu")]
public class DynamicMenu
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int dmn_id { get; set; }
public string dmn_code { get; set; }
public string dnm_parent_code { get; set; }
public string dnm_title { get; set; }
public string dnm_title_en { get; set; }
public int dnm_order { get; set; }
}
Check whether the DyanmicMenu table has primary key
Related
Good Day:
I'm trying to accomplish one to one mapping using Entity Framework but, getting this error:
The foreign key component 'Id' is not a declared property on type
'UserUpload'. Verify that it has not been explicitly excluded from the
model and that it is a valid primitive property.
This is my code below:
public abstract class Upload
{
[Key]
[Ignore]
public virtual Guid Id { get; set; }
public string Path { get; set; }
public string Name { get; set; }
public long Size { get; set; }
public UploadTypes Type { get; set; }
[Ignore]
[Timestamp]
public byte[] RowVersion { get; set; }
}
And my subclass:
public class UserUpload : Upload
{
[Key]
[ForeignKey("User")]
public override Guid Id { get { return base.Id; } set { base.Id = value; } }
public ApplicationUser User { get; set; }
}
In my abstract class, I have [Ignore] due to the fact that I want the property ignored by NEST (ElasticSearch dependency). I need this for Entity Framework nonetheless (my UserUpload).
Verify that it has not been explicitly excluded from the model
[Ignore]
[Key]
public virtual Guid Id { get; set; }
You HAVE explicitly excluded it from the model.
I would suggest to add the key configuration in the modelbuilder for that model. I found that writting there the model configuration is usually a better option.
Finally, check: 'and that it is a valid primitive property.'
Guid is not a primitive, use int instead.
I am learning C# and having trouble with viewmodels and AutoMapper.
I currently have two model classes and one viewmodel as below:
using System.ComponentModel.DataAnnotations;
namespace CarShowroom.Models
{
public class CarModel
{
[Key]
public int ModelID { get; set; }
public string Manufactuer { get; set; }
public string Model { get; set; }
public int ModelYear { get; set; }
public virtual Manufacturer manufacturer { get; set; }
public static int ManufacturerID { get; internal set; }
}
}
using System.ComponentModel.DataAnnotations;
using System.Collections.Generic;
namespace CarShowroom.Models
{
public class Manufacturer
{
[Key]
public int ManufacturerID { get; set; }
public string ManufacturerName { get; set; }
public virtual List<CarModel> carModels { get; set; }
}
}
using System.Collections.Generic;
namespace CarShowroom.Models
{
public class CarViewModel
{
public IList<CarModel> CarModel { get; set; }
public Manufacturer Manufacturer { get; set; }
}
}
The problem is when I try to add a controller using the CarViewModel class, I get the error message
CarViewModel: EntityType 'CarViewModel' has no key defined. Define the key for this EntityType.
CarViewModels: EntityType: EntitySet 'CarViewModels' is based on type 'CarViewModel' that has no keys defined.'
I have looked into how to create viewmodels online and have found you do not need to key as this is not a DB Table. Please can someone advise where I have gone wrong with making a viewmodel and why EF thinks this should be a table?
I have also tried to use AutoMapper but the tutorials I found were so old they use features which have now been removed and I have been unable to find a new tutorial which really explains how to implement the mapping and also where I should be writing the 'Maps'.
If anyone could advise on either of the two solutions so I am able to continue learning I would be very grateful as I have been stuck on this problem for weeks. I have also been looking for a small completed project/tutorial which uses AutoMapper so I can read through and understand how AutoMapper works and how/where it should be written but I am unable to find anything.
Thanks,
Danny.
My code is in Solution.Models.Worker:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace Solution.Models
{
public class Worker
{
public int AsmensKodas { get; set; }
public string Vardas { get; set; }
public string Pavarde { get; set; }
public DateTime GimimoData { get; set; }
public string Adresas { get; set; }
public bool AktyvumoPozymis { get; set; }
}
public class WorkerDBContext : DbContext
{
public DbSet<Worker> Worker { get; set; }
}
}
I changed web.config file by adding
<connectionStrings>
<add name="WorkerDBContext"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\Workers.mdf;Integrated Security=True"
providerName="System.Data.SqlClient"/>
</connectionStrings>
And when I try to add controller with "MVC 5 Controller with views, using Entity Framework" with configuration
Model class: Worker (Solution.Models)
Data context class: WorkerDbContext (Solution.Models)
Controller name: WorkersController
I get an error message saying
There was an error running the selected code generator:
'Unable to retrieve metadata for 'Solution.Models.Worker.' One or more validation errors ware detected during model generation:
Solution.Models.Worker::EntityType 'Worker' has no key defined.
Define the key for this EntityType.
Workers:EntityType:EntitySet 'Workers' is based on type 'Worker' that has no keys defined.
Any suggestions what to do or what I'm doing wrong?
One of the Model's properties should be Key. So place [Key] annotation on top of one of the properties. Like this:
public class Worker
{
[Key]
public int AsmensKodas { get; set; }
public string Vardas { get; set; }
public string Pavarde { get; set; }
public DateTime GimimoData { get; set; }
public string Adresas { get; set; }
public bool AktyvumoPozymis { get; set; }
}
Just don't forget to add this line to your using directive:
using System.ComponentModel.DataAnnotations;
Also if you have a property in your Model with name Id, you don't need to add the [Key] attribute to it.
Hello I have problems with my foreign key declaration.
App compile but i cant do "add-migration" because of an error:
The ForeignKeyAttribute on property 'TypeId' on type 'Equipment.Models.Device' is not valid. The navigation property 'DeviceDictionaryId' was not found on the dependent type 'Equipment.Models.Device'. The Name value should be a valid navigation property name
Here You can see my code:
namespace Equipment.Models
{
public class Device
{
public int DeviceId { get;set; }
[Required]
[StringLength(14)]
public string DeviceUser { get; set; }
[ForeignKey("DeviceDictionaryId")]
public int TypeId { get; set; }
}
public class DeviceDBContext: DbContext
{
public DbSet<Device> Devices {get; set;}
}
}
and second class:
namespace Equipment.Models
{
public class DeviceDictionary
{
public int DeviceDictionaryId { get; set; }
[Required]
public string DeviceManufacturer { get; set; }
[Required]
public string DeviceName { get; set; }
}
public class DeviceDictionaryDBContext : DbContext
{
public DbSet<DeviceDictionary> Dictionary { get; set; }
}
}
Can anyone suggest me needed edits?
You're creating two separate DbContext objects. Try adding just one:
public class MyDbContext: DbContext
{
public DbSet<Device> Devices {get; set;}
public DbSet<DeviceDictionary> Dictionaries { get; set; }
}
The Context must reference both Classes so that it knows about their existence. This way it can do its work, that is, set references between those classes using foreign keys.
Try this...
namespace Equipment.Models
{
public class Device
{
public int DeviceId { get;set; }
[Required]
[StringLength(14)]
public string DeviceUser { get; set; }
[ForeignKey("DeviceDictionaryId")]
public int DeviceDictionaryId { get; set; }
}
public class DeviceDBContext: DbContext
{
public DbSet<Device> Devices {get; set;}
}
}
Name the property DeviceDictionaryId as opposed to TypeId to allow The EF Conventions to do their work!
EDIT:
Just noticed after seeing the other answer that you have two seperate DBContext's!
I believe you need to change
[ForeignKey("DeviceDictionaryId")]
public int TypeId { get; set; }
to
[ForeignKey("DeviceDictionary")]
public int TypeId { get; set; }
... in other words, the annotation needs to specify the table rather than the column.
As others pointed out, you only need a single DBContext, with one DbSet for each table.
code:
using System.Data.Linq;
using System.Data.Linq.Mapping;
using System.Data.Entity;
namespace explorer.Models
{
[Table(Name = "Meta")]
public class MetaD
{
[System.ComponentModel.DataAnnotations.Key]
[Column (IsPrimaryKey=true)]
public int MId{ get; set; }
[Column]
public string Name { get; set; }
[Column]
public string Desc { get; set; }
[Column]
public DateTime? Updated { get; set; }
[Column]
public Boolean? Active { get; set; }
}
public class mContext : DbContext
{
public DbSet<MetaD> MetaData { get; set; }
}
}
The above works but when running it gives the error: The model backing the 'mContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data.
Find/Replace (IsPrimaryKey=true) to , Key