Foreign key attribute not available - c#

When attempting to create an Entity Framework database model using attributes as lined out in MS Data Developer Center, I'm unable to add the ForeignKey attribute. Do I need to add another using statement to my code?
Here's a copy of the code:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Tester.Models
{
public class MyClass
{
[Key]
public int ID { get; set; }
public string name { get; set; }
public virtual List<Note> Notes { get; set; }
public virtual List<Segment> Segments { get; set; }
}
public class Segment
{
public int ID { get; set; }
public string name { get; set; }
public virtual List<Note> segNotes { get; set; }
}
public class Note
{
public int ID { get; set; }
public DateTime notetimestamp { get; set; }
public string notestring { get; set; }
}
}

using System.ComponentModel.DataAnnotations.Schema;
Supported in .NET framework 4.5 and higher

Related

The property 'DadosRequisicao.CnpjFornecedor' could not be mapped because it is of type 'List<string>'

I'm trying to do the migration from my properties on Models, and is returning this message:
The property 'DadosRequisicao.CnpjFornecedor' could not be mapped because it is of type 'List<string>', which is not a supported primitive type or a valid entity type. Either explicitly map this property, or ignore it using the '[NotMapped]' attribute or by using 'EntityTypeBuilder.Ignore' in 'OnModelCreating'.
My code:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace PortalDeCotacao.Models
{
public class DadosRequisicao
{
[Key]
[Required]
public int Id { get; set; }
public string DataLimiteCot { get; set; }
public string ObservacoesReq { get; set; }
public List<string> CnpjFornecedor { get; set; } = new List<string>();
public List<int> CodProduto { get; set; } = new List<int>();
}
}
I didn't understand where is the problem. what should I change to migrate the properties?
You are trying to generate a One-To-Many relationship in the wrong way. You can try the following approach:
public class DadosRequisicao
{
[Key]
[Required]
public int Id { get; set; }
public string DataLimiteCot { get; set; }
public string ObservacoesReq { get; set; }
public List<CnpjFornecedor> CnpjFornecedor { get; set; } = new();
public List<CodProduto> CodProduto { get; set; } = new();
}
public class CnpjFornecedor
{
public int Id { get; set; }
public DadosRequisicao DadosRequisicao { get; set; }
public string Data { get; set; }
}
public class CodProduto
{
public int Id { get; set; }
public DadosRequisicao DadosRequisicao { get; set; }
public int Data { get; set; }
}
Now you have a correct One-To-Many relationship with navigation property.

Returning multiple joined/navigation objects

I recently inherited an ASP.NET Entity Framework API project.
I managed to do basic changes that were needed, but I'm getting a little lost with advanced SQL requests (I'm more a Symfony dev, I don't know Entity Framework).
I need to add a GET method to my API that will take a service (prestation) and will return a list of all the partners (Partenaires) who has a service (Prestation) with the same name as the GET parameter.
Here's the actual prototype of the method:
// GET: api/Partenaires_prestations
[Authorize]
public List<PartenaireMapItem> GetPartenairesWithPrestations(string prestation = "")
{
if (string.IsNullOrWhiteSpace(prestation))
{
prestation = "";
}
return db.Partenaires
.Join() // Here I don't know what to do
}
I have 3 tables that I have to use:
Prestation, Partenaires, PartenairesPrestation
Here are the 3 tables classes:
namespace Uphair.EfModel
{
using System;
using System.Collections.Generic;
public partial class Partenaire
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Partenaire()
{
this.PartenairePrestations = new HashSet<PartenairePrestation>(); // I took out the useless parts
}
public int IdPartenaire { get; set; }
[...] // I took out properties that are not needed
public virtual ICollection<PartenairePrestation> PartenairePrestations { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
}
namespace Uphair.EfModel
{
using System;
using System.Collections.Generic;
public partial class PartenairePrestation
{
public int IdPartenaire { get; set; }
public int IdPrestation { get; set; }
public double Prix { get; set; }
public int Duree { get; set; }
public Nullable<System.DateTime> DateAjout { get; set; }
public virtual Partenaire Partenaire { get; set; }
public virtual Prestation Prestation { get; set; }
}
}
namespace Uphair.EfModel
{
using System;
using System.Collections.Generic;
public partial class Prestation
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Prestation()
{
this.PartenairePrestations = new HashSet<PartenairePrestation>();
this.PrixDureeOptions = new HashSet<PrixDureeOption>();
this.LigneReservations = new HashSet<LigneReservation>();
}
public int IdPrestation { get; set; }
public string NomPrestation { get; set; }
public int Categorie { get; set; }
public Nullable<int> CoifEsthe { get; set; }
public Nullable<int> IdPrestationCategorie { get; set; }
public virtual ICollection<PartenairePrestation> PartenairePrestations { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
}
The last one makes the link between Partenaires and Prestation via IdPartenaire and IdPrestation columns.
Here's a screenshot of my model structure:
https://imageshack.com/a/img922/9111/4twiC8.png (imgur is not responding sorry)
Here's the PartenaireMapItem model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Uphair.EfModel;
namespace Uphair.Api.Models.Partenaire
{
public class PartenaireMapItem
{
public int IdPartenaire { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string NomComplet { get; set; }
public double? Lat { get; set; }
public double? Lng { get; set; }
public PartenaireType Type { get; set; }
public int DureeMin { get; set; }
public string ImageUrl { get; set; }
public int SeDeplace { get; set; }
public bool ADomicile { get; set; }
public double NoteGlobale { get; set; }
public List<String> Prestations { get; set; }
}
}
I need to use join to get a list of partners (Partenaires) that have the service (Prestation) with the service name provided in the GET parameter, but I don't know how to do it.
Any help would be welcome, thanks to anyone who will take the time to read/answer me.

How do i create Foreign Key relationship in .netframework 3.5/Code First Model?

I have below data contract with foreign key relation with my .net framework 4.0 project. I want to re-use the same code for .net framework 3.5 project. But i am dll missing error for ForeignKey attribute. How do i rewrite the below code for .netframework 3.5? Kindly help.
using System;
using System.Collections.Generic;
Using System.ComponentModel.DataAnnotations;
Using System.ComponentModel.DataAnnotations.Schema;
namespace xyz {
[DataContract]
public class Category
{
public string category_id { get; set; }
public string category_name { get; set; }
public virtual ICollection<SubCategory> SubCategorys { get; set; }
}
[DataContract]
public class SubCategory
{
public string sub_category_id { get; set; }
public string sub_category_name { get; set; }
public virtual ICollection<SubCategory2> SubCategory2s { get; set; }
[ForeignKey("category_id")]
public virtual Category Category { get; set; }
}
[DataContract]
public class SubCategory2
{
public string sub_category2_id { get; set; }
public string sub_category2_name { get; set; }
[ForeignKey("sub_category_id")]
public virtual SubCategory SubCategory { get; set; }
}
}

Entity Framework foreign key not found during migration

I'm experiencing an unexpected error when setting up a migration after adding keys and foreign keys to my data model. I'm using VS2013 Express, with .NET framework 4.5.
When creating a data model for Entity Framework, because the relationship keys between classes aren't what is expected by convention, I'm using data annotations as outlined in the MS Data Developer Center. Here's the class code:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace BacklogTracker.Models
{
public class WorkOrder
{
[Key]
public string woNum { get; set; }
public string woClosingStatus { get; set; }
[ForeignKey("ID")]
public virtual ICollection<Note> woNotes { get; set; }
[ForeignKey("machSN")]
public virtual Machine woMachine { get; set; }
[ForeignKey("ID")]
public virtual ICollection<Segment> woSegments { get; set; }
}
public class Machine
{
[Key]
public string machSN { get; set; }
public string machLocation { get; set; }
public string machModel { get; set; }
}
public class Segment
{
[Key]
public int ID { get; set; }
public uint segNum { get; set; }
public string segRepair { get; set; }
[ForeignKey("ID")]
public virtual ICollection<Note> segNotes { get; set; }
}
public class Note
{
[Key]
public int ID { get; set; }
public DateTime notetimestamp { get; set; }
public string notestring { get; set; }
}
}
However, when I try to perform a migration after updating the model by performing enable-migrations in the package manager console, I get the following error:
The ForeignKeyAttribute on property 'woMachine' on type
'BacklogTracker.Models.WorkOrder' is not valid. The foreign key name
'machSN' was not found on the dependent type
'BacklogTracker.Models.WorkOrder'. The Name value should be a comma
separated list of foreign key property names.
Why is my foreign key name 'machSN' not being found?
I think you have some errors in your model. Default Code First convention for ForeignKey relationship expected to have declared a foreign key property in the dependend end (WorkOrder) that match with primary key property of the principal end (Machine). It is not necessary that they have the same name, check this link. So, declare a property named machSN in your WorkOrder class:
public class WorkOrder
{
[Key]
public string woNum { get; set; }
public string woClosingStatus { get; set; }
public virtual ICollection<Note> woNotes { get; set; }
public string machSN { get; set; }
[ForeignKey("machSN")]
public virtual Machine woMachine { get; set; }
public virtual ICollection<Segment> woSegments { get; set; }
}
You can find other errors in the woNotes and woSegments navigation properties. In this side of a one-to-many relationship you don't declare a FK, is in the other side, in Note and Segment classes, for example:
public class Note
{
[Key]
public int ID { get; set; }
public DateTime notetimestamp { get; set; }
public string notestring { get; set; }
[ForeignKey("Order)]
public string woNum { get; set; }
public virtual WorkOrder Order{get;set;}
}
Delete also in the Segment class the ForeignKey attribute over segNotes navigation property for the same reasons explained before.
public class Segment
{
[Key]
public int ID { get; set; }
public uint segNum { get; set; }
public string segRepair { get; set; }
public virtual ICollection<Note> segNotes { get; set; }
}

EF 5 - The number of primary key values passed must match the number of primary key values defined on the entity

I ran into this error message while using EF5. Wondering if anyone has the answer for this.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Budget.Data
{
[Table("BudgetItems")]
public class BudgetItemRepository
{
[Column("MdaCode")]
public int MDACode { get; set; }
[Column("PersonalCost")]
public double PersonnelCost { get; set; }
[Column("OverheadCost")]
public double OverheadCost { get; set; }
[Column("RecurrentCost")]
public int RecurrentCost { get; set; }
[Column("CapitalCost")]
public double Capital { get; set; }
public double Allocation { get; set; }
[Column("BudgetYear")]
public String BudgetYear { get; set; }
[Column("RecordCreatedDate")]
public DateTime DateCreated { get; set; }
[Column("RecordLastModifiedDate")]
public DateTime LastModifiedDate { get; set; }
public virtual IList<BudgetItemRepository> budgetitems { get; set; }
public virtual IList<BudgetLineItemRepository> budgetlineitems { get; set; }
[Column("BudgetItemID")]
public int Id { get; set; }
}
}
You didn't declare a primary key for the entity. You do this by marking the primary key column with the [Key} attribute. Assuming this is the Id property, the code would look like:
[Column("BudgetItemID")]
[Key]
public int Id { get; set; }

Categories

Resources