ForeignKey attribute is not valid error - c#

Can you help me?
namespace mvcAmerica.Models
{
public class ArtModels
{
[Key]
public int idArt { get; set; }
[Required(ErrorMessage="Codigo del Articulo es Requerido")]
public string co_art { get; set; }
[Required]
public string des_art { get; set; }
[Required]
public string modelo { get; set; }
[Required]
public string referencia { get; set; }
[ForeignKey("LineaModels")]
public int IdLinea { get; set; }
public LineaModels Linea { get; set; }
}
public class LineaModels
{
[Key]
public int IdLinea { get; set; }
[Required(ErrorMessage="Indique el Codigo")]
public string co_lin { get; set; }
[Required(ErrorMessage = "Indique la Descripción")]
public string des_lin { get; set; }
}
}
Error:
The ForeignKeyAttribute on property 'IdLinea' on type
'mvcAmerica.Models.ArtModels' is not valid. The navigation property
'LineaModels' was not found on the dependent type
'mvcAmerica.Models.ArtModels'. The Name value should be a valid
navigation property name.

You need to change this:
[ForeignKey("LineaModels")]
public int IdLinea { get; set; }
public LineaModels Linea { get; set; }
To this:
[ForeignKey("Linea")]
public int IdLinea { get; set; }
public virtual LineaModels Linea { get; set; }
It needs to match the property name.
Edit
I've just created the following application with no problems:
public class ArtModels
{
[Key]
public int idArt { get; set; }
[Required(ErrorMessage = "Codigo del Articulo es Requerido")]
public string co_art { get; set; }
[Required]
public string des_art { get; set; }
[Required]
public string modelo { get; set; }
[Required]
public string referencia { get; set; }
[ForeignKey("Linea")]
public int IdLinea { get; set; }
public virtual LineaModels Linea { get; set; }
}
public class LineaModels
{
[Key]
public int IdLinea { get; set; }
[Required(ErrorMessage = "Indique el Codigo")]
public string co_lin { get; set; }
[Required(ErrorMessage = "Indique la Descripción")]
public string des_lin { get; set; }
}
public class AppContext : DbContext
{
public DbSet<ArtModels> ArtModelses { get; set; }
public DbSet<LineaModels> LineaModelses { get; set; }
}
So you must be missing something else?

You have to change this:
[ForeignKey("LineaModels")]
public int IdLinea { get; set; }
To this:
[ForeignKey("Linea")]
public int IdLinea { get; set; }
The ForeignKey name has to be the same as your navigation property (here Linea).

Related

AutoMapperMappingException: Missing type map configuration or unsupported mapping

I'm attempting to use AutoMapper for the first time. The GSMSite maps fine, but I get an error when trying to map the GSMUnit:
AutoMapperMappingException: Missing type map configuration or unsupported mapping.
Do I need to specify a relationship between GSMSite and GSMUnits?
Domain class:
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string Company { get; set; }
public string Telephone { get; set; }
public bool PasswordReset { get; set; } = false;
public virtual ICollection<GSMSite> GSMSites { get; set; }
}
public class GSMSite
{
public int Id { get; set; }
public string SiteName { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string Town { get; set; }
public string Postcode { get; set; }
public string ContactName { get; set; }
public string ContactNumber { get; set; }
public string ContactEmail { get; set; }
public string ApplicationUserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public virtual ICollection<GSMUnit> GSMUnits { get; set; }
}
public class GSMUnit
{
public int Id { get; set; }
public string Model { get; set; }
public string Firmware { get; set; }
public string TelephoneNum { get; set; }
public int GSMSiteId { get; set; }
public virtual GSMSite GSMSite { get; set; }
}
Contract class:
public class GSMResponse
{
public int Id { get; set; }
public string Model { get; set; }
public string Firmware { get; set; }
public string TelephoneNum { get; set; }
}
public class SiteResponse
{
public int Id { get; set; }
public string SiteName { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string Town { get; set; }
public string Postcode { get; set; }
public string ContactName { get; set; }
public string ContactNumber { get; set; }
public string ContactEmail { get; set; }
}
Mapping:
public DomainToResponseProfile()
{
CreateMap<GSMSite, SiteResponse>();
CreateMap<GSMUnit, GSMResponse>();
}

deserialization json newtonsoft leaves the object with everything in null C #

Greetings I have the following problem it turns out that I try to deserialize a json with the newtonsoft library with the following line
Tramite body = JsonConvert.DeserializeObject < Tramite> (JsonBody);
Json which is sent:
{
"body":[
{
"id":3772,
"processInstanceId":"1416",
"tipoTramite":{
"id":1,
"descripcion":"Solicitud Patente Comercial (Municipalidad)"
},
"canal":{
"id":0,
"nombre":""
},
"definicionTramite":{
"id":282,
"tipoTramite":null,
"idEstado":0,
"version":3,
"idDepartamento":0,
"idArea":0,
"nombre":"Solicitud Patente Comercial (Municipalidad)",
"codigo":null,
"descripcion":null,
"deploymentId":null,
"configuracion":null,
"processId":null
},
"institucion":{
"id":1045,
"idInstitucionBase":null,
"tipoInstitucion":null,
"nombre":"Municipalidad de La Granja",
"codigo":"LAGRANJA",
"direccion":null,
"logoWeb":null,
"logoPdf":null,
"telefonoFijo":null,
"email":null,
"propietario":null
},
"idDepartamento":1,
"idArea":3,
"estado":{
"id":294,
"definicionTramite":{
"id":282,
"tipoTramite":null,
"idEstado":0,
"version":0,
"idDepartamento":0,
"idArea":0,
"nombre":null,
"codigo":null,
"descripcion":null,
"deploymentId":null,
"configuracion":null,
"processId":null
},
"codigo":"03",
"nombre":"En Proceso"
},
"cve":"3df31748ec86df4280ecfaa853ead07a8918b345",
"numeroSolicitud":"555",
"tarifa":0,
"rut":{
"numero":13639987,
"dv":"K"
},
"rutEmpresa":{
"numero":76291578,
"dv":"2"
},
"nombre":"Solicitud Patente Comercial (Municipalidad)",
"flagPagado":false,
"fechaCreacion":1508792522683,
"fechaModificacion":1508792809726,
"datosTramite":[
{
"id":0,
"key":"inmueble_direccion_numero",
"tipo":"string",
"data":"3334"
}
],
"deploymenId":"cl.corfo.municipiogenerico:bpm-patentegenerica:1.4",
"processId":"patenteGenerica",
"solicitante":"FÉLIX EDUARDO CIFUENTES CID",
"contribuyente":"NombreMock de Fantasia",
"keyConfiguracion":"patente-comercial-ampliacion-giro"
}
]
}
This is the object: https://i.stack.imgur.com/MTT9s.png
Clase que serializo:
public int id { get; set; }
public string processInstanceId { get; set; }
Dictionary<string, string> tipoTramite { get; set; }
Dictionary<string, string> canal { get; set; }
public DefinicionTramite definicionTramite { get; set; }
public Institucion institucion { get; set; }
public int idDepartamento { get; set; }
public int idArea { get; set; }
public Estado estado { get; set; }
public string cve { get; set; }
public string numeroSolicitud { get; set; }
public double tarifa { get; set; }
Dictionary<string, string> rut { get; set; }
Dictionary<string, string> rutEmpresa { get; set; }
public string nombre { get; set; }
public bool flagPagado { get; set; }
public string fechaCreacion { get; set; }
public string fechaModificacion { get; set; }
public List<DatosTramite> datosTramite { get; set; }
public string deploymenId { get; set; }
public string processId { get; set; }
public string solicitante { get; set; }
public string contribuyente { get; set; }
public string keyConfiguracion { get; set; }
class Definicion Tramite
public int id { get; set; }
public string tipoTramite { get; set; }
public int idEstado { get; set; }
public int version { get; set; }
public int idDepartamento { get; set; }
public int idArea { get; set; }
public string nombre { get; set; }
public string codigo { get; set; }
public string descripcion { get; set; }
public string deploymentId { get; set; }
public string configuracion { get; set; }
public string processId { get; set; }
class Institucion
public int id { get; set; }
public string idInstitucionBase { get; set; }
public string tipoInstitucion { get; set; }
public string nombre { get; set; }
public string codigo { get; set; }
public string direccion { get; set; }
public string logoWeb { get; set; }
public string logoPdf { get; set; }
public string telefonoFijo { get; set; }
public string email { get; set; }
public string propietario { get; set; }
class Estado
public int id { get; set; }
public DefinicionTramite definicionTramite { get; set; }
public string codigo { get; set; }
public string nombre { get; set; }
class Datos Tramite
public int id { get; set; }
public string key { get; set; }
public string tipo { get; set; }
public string data { get; set; }
These are all the classes that are involved in the deserialization of the json that I sent, I tried to deserialize a dataSet but it also could not because of the classes it contained (according to what I read in a stackoverflow question) if someone knows that I am bad or if there is another way of doing the deserialization of a json in C# helps me
This worked for me:
JsonConvert.DeserializeObject<Rootobject>(json)
Here are the classes that I created:
public class Rootobject
{
public Body[] body { get; set; }
}
public class Body
{
public int id { get; set; }
public string processInstanceId { get; set; }
public Tipotramite tipoTramite { get; set; }
public Canal canal { get; set; }
public Definiciontramite definicionTramite { get; set; }
public Institucion institucion { get; set; }
public int idDepartamento { get; set; }
public int idArea { get; set; }
public Estado estado { get; set; }
public string cve { get; set; }
public string numeroSolicitud { get; set; }
public int tarifa { get; set; }
public Rut rut { get; set; }
public Rutempresa rutEmpresa { get; set; }
public string nombre { get; set; }
public bool flagPagado { get; set; }
public long fechaCreacion { get; set; }
public long fechaModificacion { get; set; }
public Datostramite[] datosTramite { get; set; }
public string deploymenId { get; set; }
public string processId { get; set; }
public string solicitante { get; set; }
public string contribuyente { get; set; }
public string keyConfiguracion { get; set; }
}
public class Tipotramite
{
public int id { get; set; }
public string descripcion { get; set; }
}
public class Canal
{
public int id { get; set; }
public string nombre { get; set; }
}
public class Definiciontramite
{
public int id { get; set; }
public object tipoTramite { get; set; }
public int idEstado { get; set; }
public int version { get; set; }
public int idDepartamento { get; set; }
public int idArea { get; set; }
public string nombre { get; set; }
public object codigo { get; set; }
public object descripcion { get; set; }
public object deploymentId { get; set; }
public object configuracion { get; set; }
public object processId { get; set; }
}
public class Institucion
{
public int id { get; set; }
public object idInstitucionBase { get; set; }
public object tipoInstitucion { get; set; }
public string nombre { get; set; }
public string codigo { get; set; }
public object direccion { get; set; }
public object logoWeb { get; set; }
public object logoPdf { get; set; }
public object telefonoFijo { get; set; }
public object email { get; set; }
public object propietario { get; set; }
}
public class Estado
{
public int id { get; set; }
public Definiciontramite1 definicionTramite { get; set; }
public string codigo { get; set; }
public string nombre { get; set; }
}
public class Definiciontramite1
{
public int id { get; set; }
public object tipoTramite { get; set; }
public int idEstado { get; set; }
public int version { get; set; }
public int idDepartamento { get; set; }
public int idArea { get; set; }
public object nombre { get; set; }
public object codigo { get; set; }
public object descripcion { get; set; }
public object deploymentId { get; set; }
public object configuracion { get; set; }
public object processId { get; set; }
}
public class Rut
{
public int numero { get; set; }
public string dv { get; set; }
}
public class Rutempresa
{
public int numero { get; set; }
public string dv { get; set; }
}
public class Datostramite
{
public int id { get; set; }
public string key { get; set; }
public string tipo { get; set; }
public string data { get; set; }
}
You need to see your JSON and figure out that body is an array and a root. Hence there must be a root class with body as an array. Create that and then deserialize. That must work
First of all, your C# model is not entirely same as your JSON. For Example, tipoTramite in your main class and Json object are different. Secondly, the reason why you are getting everything null here is you are sending an array of object in the json but at the server level, you are deserializing the object. You could do one of the following:
1.Send JSON as object and not as array like below, and then your code should work
{
"body":{
"id":3772,
"processInstanceId":"1416",
...
...
...
}
2.If you don't want to change the json, then for deserializing, you will have to create a class that contains the array of Tramite type and then use that class to deserialize the json:
public class TramiteJsonModel{
public Tramite[] Body {get;set;}
}
Now use the code below to deserialize the content:
TramiteJsonModel body = JsonConvert.DeserializeObject <TramiteJsonModel> (JsonBody);

Entity framework not creating join table

I will appreciate if somebody can tell me why entity framework is not creating join table for following model. It is creating table for type and feature but not the table that will join them.
public class DeviceType
{
[Display(Name = "ID")]
public int DeviceTypeID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public IEnumerable<DeviceFeature> DeviceFeatures { get; set; }
}
public class DeviceFeature
{
[Display(Name = "ID")]
public int DeviceFeatureID { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
public IEnumerable<DeviceType> DeviceTypes { get; set; }
}
public class DeviceFeatureView
{
public virtual IEnumerable<DeviceType> DeviceTypes { get; set; }
public virtual IEnumerable<DeviceFeature> DeviceFeatures { get; set;
}
You do not need the bridge to create a many-to-many relationship. EF will figure it out. Change the type of the navigation properties from IEnumerable to ICollection like this:
public class DeviceType
{
public DeviceType()
{
this.DeviceFeatures = new HashSet<DeviceFeature>();
}
[Display(Name = "ID")]
public int DeviceTypeID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public ICollection<DeviceFeature> DeviceFeatures { get; set; }
}
public class DeviceFeature
{
public DeviceFeature()
{
this.DeviceTypes = new HashSet<DeviceType>();
}
[Display(Name = "ID")]
public int DeviceFeatureID { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
public ICollection<DeviceType> DeviceTypes { get; set; }
}
More about it here.

Why i get System.Data.Entity.ModelConfiguration.ModelValidationException in EF 6

My model is defined like this:
{
[Key]
[DatabaseGenerated (DatabaseGeneratedOption.None)]
//[HiddenInput(DisplayValue = false)]
public string ODID { get; set; }
[Required(ErrorMessage = "Введите ИНН")]
public long AuthorityINN { get; set; }
public int AuthorityID { get; set; }
[Required(ErrorMessage = "Введите наименование набора данных")]
public string Name { get; set; }
[Required(ErrorMessage = "Введите краткое описание")]
public string Description { get; set; }
[DataType(DataType.MultilineText)]
[Required(ErrorMessage = "Введите полное описание")]
public string FullDescription { get; set; }
public int CategoryID { get; set; }
public bool IsPublished { get; set; }
//public int OwnerID {get;set;}
public Periodicity Periodicity { get; set; }
public string KeyWords { get; set; }
public int UserID { get; set; }
public DateTime CreateDate { get; set; }
public bool HasGeo { get; set; }
public long Reviews { get; set; }
public long Downloads { get; set; }
}
But I catch a System.Data.Entity.ModelConfiguration.ModelValidationException exception with a message:
Define key for this EntityType.
What could be the issue?

How do I setup navigation properties - Code First - Entity Framework?

I have the following models. I'm trying to use Code First New Database approach with ASP.NET MVC 5.
Client.cs
public class Client
{
public int ID { get; set; }
public int Name { set; get; }
public string Phone { set; get; }
public string Email { get; set; }
public string Address { set; get; }
public Ibo IboID { set; get; }
public DateTime LastOrder { get; set; }
public virtual ICollection<Ibo> Ibo { set; get; }
}
Ibo.cs
public class Ibo
{
[Key]
public int IboID { set; get; }
[Required]
[Display(Name="Full Name")]
public string Name { set; get; }
[Required]
[RegularExpression(#"^\d+$", ErrorMessage = "The IBO number you've input must contain only numbers.")]
[Display(Name = "IBO Number")]
public string IboNumber { set; get; }
[Required]
[StringLength(100, ErrorMessage = "The Phone number must be at least {2} numbers long.", MinimumLength = 7)]
public string Phone { set; get; }
[Required]
public string Address { set; get; }
[Required]
[NotMapped]
public string Username { set; get; }
[Required]
[UIHint("EmailAddressAttribute")]
[NotMapped]
public string Email { set; get; }
[Required]
[DataType(DataType.Password)]
public string Password { set; get; }
[Display(Name="Confirm Password")]
[DataType(DataType.Password)]
[Compare("Password")]
[NotMapped]
public string PasswordConfirm { set; get; }
[NotMapped]
public string SelectedSecurityQ { set; get; }
[Display(Name="Security Question")]
public int SecurityQuestionID { set; get; }
[Required]
[Display(Name="Your answer")]
public string SecurityAnswer { set; get; }
public virtual SecurityQuestions SecurityQuestions { set; get; }
}
Mods.cs
public class Mods
{
public int ModsID { set; get; }
public int IboID { set; get; }
public virtual ICollection<Ibo> Ibo { set; get; }
}
Order.cs
public class Order
{
public int OrderID { set; get; }
public int IboID { set; get; }
public int ClientID { set; get; }
public DateTime Created { set; get; }
public DateTime Modified { set; get; }
public virtual ICollection<Ibo> Ibo { set; get; }
public virtual ICollection<Client> Client { set; get; }
}
OrderProcess.cs
public class OrderProcess
{
public int OrderProcessID {set; get;}
public int OrderID { set; get; }
public DateTime TimeStamp { set; get; }
public int ProductID { set; get; }
public int State { set; get; }
public decimal ProductCost { set; get; }
public virtual ICollection<Order> Order { set; get; }
public virtual ICollection<Product> Product { set; get; }
}
Product.cs
public class Product
{
public int ID;
public string ProductID;
public string ProductName;
public string ProductDesc;
public decimal Pv;
public decimal Bv;
public decimal PriceIbo_2014_09;
public decimal PriceSug_2014_09;
//If Product is taxable
public bool Tax;
public int State;
public decimal Price_Ibo_2014_09;
public decimal Price_Sug_2014_09;
public int Status;
}
SecurityQuestions.cs
public class SecurityQuestions
{
public int ID { set; get; }
public string SecurityQuestion { set; get; }
public virtual ICollection<Ibo> Ibo { get; set; }
}
What I'm trying to do is to set the following relations. I'm very confused on when and how to use ICollection<>, List<> or similars with the virtual keyboard.
I'm also trying to generate a new IboID entry in the Ibo table when a new user is created in the AspNetUsers table.
Something like this:
public virtual ICollection<Ibo> Iboes
Any references, suggestions will be kindly appreciated! Thanks in advance

Categories