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

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?

Related

Display two table data in one

Hi doing a master details and currently in the process of display two tables data based on invoice number but I have this error
An exception of type 'System.Data.Entity.Core.EntityCommandExecutionException' occurred in EntityFramework.SqlServer.dll but was not handled in user code
{"Invalid column name 'klsm_Invoice_InternalInvoiceNo'.\r\nInvalid column name 'klsm_Invoice_InternalInvoiceNo'.\r\nInvalid column name 'klsm_Invoice_InternalInvoiceNo'."}
I am following Tutorial: Implement CRUD Functionality with the Entity Framework in ASP.NET MVC but I have come to a problem.
Desc class
[Table("klsm_InvoiceDesc")]
public class Desc
{
[Key]
public string InternalInvoiceNo { get; set; }
public string InvoiceNo { get; set; }
public int DescNo { get; set; }
public string Principal { get; set; }
public string ChargeCode { get; set; }
public string Quantity { get; set; }
public string Description { get; set; }
public string UnitPrice { get; set; }
public string Amount { get; set; }
public string ForeignAmount { get; set; }
public string EL1 { get; set; }
public string EL2 { get; set; }
public string ShortName { get; set; }
public string InvoiceType { get; set; }
public string PONumber { get; set; }
public string Batch { get; set; }
public string CCVBatch { get; set; }
public string PaidAmount { get; set; }
public string Paid { get; set; }
public string TT { get; set; }
public string BankCode { get; set; }
//public string Id { get; set; }
public virtual College klsm_Invoice{ get; set; }
}
College class
[Table("klsm_Invoice")]
public class College
{
[Key]
public string InternalInvoiceNo { get; set; }
public string InvoiceNo { get; set; }
public DateTime InvoiceDate { get; set; }
public string CustomerName { get; set; }
public int Year { get; set; }
public int Month { get; set; }
public decimal Amount { get; set; }
public decimal ForeignAmount { get; set; }
public string UserCreated { get; set; }
public string UserModified { get; set; }
public int AccMonth { get; set; }
public int AccYear { get; set; }
public string AccStatus { get; set; }
public string Status { get; set; }
public string PaidStatus { get; set; }
public string Principal { get; set; }
public DateTime DateCreated { get; set; }
public DateTime DateModified { get; set; }
public string EL1 { get; set; }
public string InvoiceType { get; set; }
public string CurrencyType { get; set; }
public decimal ExchangeRate { get; set; }
public string GSTChecked { get; set; }
public DateTime PaymentSchedule { get; set; }
public string PaymentMode { get; set; }
public string CashAdvance { get; set; }
public virtual ICollection<Desc> klsm_InvoiceDesc { get; set; }
}
Home Controller
public ActionResult Details(string id)
{
College klsm_Invoice = db.klsm_Invoice.Find(id);
return View(klsm_Invoice);
}

Cannot implicitly convert type 'System.Collections.Generic.List<int>' to 'System.Collections.Generic.IEnumerable<Model>'

When using Select() I am getting this error
Cannot implicitly convert type 'System.Collections.Generic.List<int>' to 'System.Collections.Generic.IEnumerable<OgrenciEvi.Areas.Message.Models.MessageModel>'.
SiteContext db = new SiteContext();
[Route]
public ActionResult Index()
{
var model = new ViewModel();
int UserID = int.Parse(User.Identity.GetID());
model.Messages = db.Message.Where(m => m.ReceiverID == UserID || m.SenderID == UserID).Select(m=>m.SenderUser.Name).ToList();
return View(model);
}
How I fix it ?
Edit:
public class MessageModel
{
[Key]
public int MessageID { get; set; }
[Required(ErrorMessage = "Boş mesaj gönderilemez.")]
public string MessageContent { get; set; }
[Required]
public int SenderID { get; set; }
[Required]
public int ReceiverID { get; set; }
[Required]
public DateTime SendingDate { get; set; }
[Required]
public bool IsSeen { get; set; }
public virtual UserModel SenderUser { get; set; }
public virtual UserModel ReceiverUser { get; set; }
MessageModel() {
SendingDate = DateTime.Now;
}
}
userModel:
public class UserModel
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int UserID { get; set; }
[Required (ErrorMessage ="İsim alanı boş geçilemez.")]
public string Name { get; set; }
[Required(ErrorMessage = "Soyadı alanı boş geçilemez.")]
public string Surname { get; set; }
[RegularExpression(#"^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}" +
#"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +
#".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
ErrorMessage = "E-Posta adresi geçersiz.")]
[DataType(DataType.EmailAddress)]
public string Mail { get; set; }
[DataType(DataType.Password)]
public string Password { get; set; }
[NotMapped] // Does not effect with your database
public string ConfirmPassword { get; set; }
public int Gender { get; set; }
[RegularExpression("^[0-9]*$", ErrorMessage ="Telefon numarası geçersiz.")]
public string PhoneNumber{ get; set; }
public int SmokeStatus { get; set; }
public DateTime RegistrationDate { get; set; }
[HiddenInput(DisplayValue = false)]
public string ReturnUrl{ get; set; }
[Range(1900,2000, ErrorMessage ="Doğum yılı 1900 ile 2000 yılları arasında olmalı.")]
[Required(ErrorMessage ="Yaş alanı boş geçilemez.")]
public int BirthYear { get; set; }
public string FacebookID { get; set; }
public bool Manager { get; set; }
public int AccessFacebook { get; set; }
public int AccessInstagram { get; set; }
public int AccessPhoneNumber { get; set; }
public int AccessTwitter { get; set; }
public List<LookingForaMateModel> LFMate { get; set; }
public List<LookingForaHome> LFHome { get; set; }
public List<AlbumModel> Album { get; set; }
public List<PropertyTransferModel> PropertyTransfer{ get; set; }
[ForeignKey("SenderID")]
public List<MessageModel> SenderUser { get; set; }
[ForeignKey("ReceiverID")]
public List<MessageModel> ReceiverUser { get; set; }
public UserModel() {
RegistrationDate = DateTime.Now;
}
}
I want "direct message" for my web site and the design look like facebook messenger so there is a panel on left side. I should get list Message's sender name and last message. But I couldn't make it :)
You still havn't shown your code for the ViewModel class. But Assuming that model.Messages is of type List<Message>, the following should work:
var model = new ViewModel();
int UserID = int.Parse(User.Identity.GetID());
model.Messages = db.Message.Where(m => m.ReceiverID == UserID || m.SenderID == UserID).ToList();
Make Messages type IEnumerable

Entity Framework CodeFirst create relationship between 2 table on non primary key

Hello I am trying to add a migration and change the primary key of the table not to primary key as this has just become a requirement. Now that said it will always be unique, but needs to have a one to many relationship. with other tables and cascade on update.
I have found this but this isn't using DataAnnotations which i am, and want to contenue to do so.
Here are the 2 classes in question.
public partial class MProcurement
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public MProcurement()
{
Logs = new List<MLog>();
}
[Key]
public int Id { get; set; }
[Required]
[StringLength(8)]
[Index(IsUnique = true)]
public string ParcelId { get; set; } //current primary key that i want to change
[Required]
public DateTime PurchaseDate { get; set; }
[Required]
public string UserId { get; set; }
[Required]
[StringLength(10)]
public string ProducerCode { get; set; }
public FscCertType FscCertType { get; set; }
public int CountyId { get; set; }
[Required]
[StringLength(5)]
public string Zip { get; set; }
public Scale ProducerScale { get; set; }
public Scale Scale { get; set; }
public Terms Terms { get; set; }
public bool UseProducerScale { get; set; }
[ForeignKey(nameof(UserId))]
public virtual MUser User { get; set; }
[ForeignKey(nameof(ProducerCode))]
public virtual MProducer Producer { get; set; }
[ForeignKey(nameof(CountyId))]
public virtual MCounty County { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual List<MLog> Logs { get; set; }
}
public partial class MLog
{
public int Id { get; set; }
public int? Tag { get; set; }
[Required]
[MinLength(8), MaxLength(8)]
[Index("IX_Proc_Seq", 1, IsUnique = true)]
[ForeignKey(nameof(MProcurement.ParcelId))]//would like to add to MProcurement as ForignKey
public string ProcurementId { get; set; }
[Required]
public DateTime PurchaseDate { get; set; }
public Scale Scale { get; set; }
[Required]
[Index("IX_Proc_Seq",2,IsUnique = true)]
public int Seq { get; set; }
public bool DoubleLength { get; set; }
[Required]
[MaxLength(4)]
public string SpecieId { get; set; }
[Required]
public int CategoryId { get; set; }
[Required]
[MaxLength(1)]
public string Grade { get; set; }
[Required]
public int Length { get; set; }
[Required]
public int CutbackLength { get; set; }
[Required]
public int CutbackFeet { get; set; }
[Required]
public int Diameter { get; set; }
public int? Pounds { get; set; }
[Required]
public int Feet { get; set; }
[Required]
public decimal NetCost { get; set; }
[Required]
public decimal AdjCostPerFoot { get; set; }
[Required]
public decimal AdjustedNet { get; set; }
[Required]
public decimal ProducerPricePerFoot { get; set; }
[Required]
public decimal CostPerFoot { get; set; }
[Required]
public int ProducerFeet { get; set; }
public virtual MCategory Category { get; set; }
public virtual MSpecie Specie { get; set; }
public virtual MProcurement Procurement { get; set; }
}

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

ForeignKey attribute is not valid error

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).

Categories