Composite key in table manupulation in Entity Framework - entity-framework

I use Entity Framework 5 Code First and have some problem with composite keys.
I have those tables
And this is how i map the entities
public class Product : EntityBase
{
public Product()
{
this.ProductArticles = new List<ProductArticle>();
}
[Key, Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ProductId { get; set; }
[Key, Column(Order = 1)]
public int PricelistId { get; set; }
public string Description { get; set; }
public string Unit { get; set; }
public string ReportText1 { get; set; }
public string ReportText2 { get; set; }
public bool Standard { get; set; }
public int ProductGroupId { get; set; }
public decimal? Surcharge1 { get; set; }
public decimal? Surcharge2 { get; set; }
public decimal? Surcharge3 { get; set; }
public decimal? Surcharge4 { get; set; }
public decimal PriceMaterialIn { get; set; }
public decimal AdjMaterialIn { get; set; }
public decimal F_PriceMaterialInAdj { get; set; }
public decimal F_AdjMaterial { get; set; }
public decimal F_PriceMaterialOut { get; set; }
public decimal PriceArtisanIn { get; set; }
public decimal F_AdjArtisan { get; set; }
public decimal F_PriceArtisanOut { get; set; }
public decimal F_TotalOut { get; set; }
public decimal F_TotalOutVat { get; set; }
public bool GetPrice { get; set; }
public string Notes { get; set; }
[ForeignKey("ProductGroupId,PricelistId")]
public virtual ProductGroup ProductGroup { get; set; }
[ForeignKey("ProductId,PricelistId")]
public virtual ICollection<ProductArticle> ProductArticles { get; set; }
[ForeignKey("PricelistId")]
public virtual Pricelist Pricelist { get; set; }
}
public class ProductGroup : EntityBase
{
[Key, Column(Order = 0)]
public int ProductGroupId { get; set; }
[Key, Column(Order = 1)]
public int PricelistId { get; set; }
public int OptionalGroupId { get; set; }
public string Prefix { get; set; }
public string Description { get; set; }
public decimal? Surcharge1 { get; set; }
public decimal? Surcharge2 { get; set; }
public decimal? Surcharge3 { get; set; }
public decimal? Surcharge4 { get; set; }
public string ReportText1 { get; set; }
public string ReportText2 { get; set; }
[ForeignKey("OptionalGroupId,PricelistId")]
public virtual OptionalGroup OptionalGroup { get; set; }
[ForeignKey("PricelistId")]
public virtual Pricelist Pricelist { get; set; }
}
But when the context is build i get this message
337,10) : error 3015: Problem in mapping fragments starting at lines
303, 337:Foreign key constraint 'Product_ProductGroup' from table
Product (PricelistId, ProductGroupId) to table ProductGroup
(ProductGroupId, PricelistId):: Insufficient mapping: Foreign key must
be mapped to some AssociationSet or EntitySets participating in a
foreign key association on the conceptual side.

I solved it by redesign the table. Think that composite key are bad design.

Related

Code first one-to-many relationship with restraints

I have the following one-to-many database structure generated by code first. Many Buttons can be added with a relation back to a single GSMUnit. BtnNo should be unique (for every GSMUnitId), and shouldn't be duplicated. Currently it is possible to duplicate. how can i prevent this?
public class GSMUnit
{
public int Id { get; set; }
[MaxLength(20)]
public string Model { get; set; }
[MaxLength(40)]
public string GsmName { get; set; }
[MaxLength(40)]
public string TelephoneNum { get; set; }
public int GSMSiteId { get; set; }
public virtual GSMSite GSMSite { get; set; }
public virtual GSMSetting GSMSettings { get; set; }
public virtual ICollection<Button> Buttons { get; set; }
}
public class Button
{
public int Id { get; set; }
[MaxLength(30)]
public string Primary { get; set; }
[MaxLength(30)]
public string Divert1 { get; set; }
[MaxLength(30)]
public string Divert2 { get; set; }
[MaxLength(30)]
public string Divert3 { get; set; }
[MaxLength(20)]
public string AptNo { get; set; }
[MaxLength(10)]
public string Code { get; set; }
[MaxLength(4)]
public string DTO { get; set; }
[MaxLength(4)]
public string Timeband { get; set; }
[MaxLength(15)]
public string BtnNo { get; set; }
[MaxLength(20)]
public string AptName { get; set; }
public int GSMUnitId { get; set; }
public virtual GSMUnit GSMUnit { get; set; }
}
You can use the Index attribute for that:
public class Button
{
public int Id { get; set; }
[MaxLength(30)]
public string Primary { get; set; }
[MaxLength(30)]
public string Divert1 { get; set; }
[MaxLength(30)]
public string Divert2 { get; set; }
[MaxLength(30)]
public string Divert3 { get; set; }
[MaxLength(20)]
public string AptNo { get; set; }
[MaxLength(10)]
public string Code { get; set; }
[MaxLength(4)]
public string DTO { get; set; }
[MaxLength(4)]
public string Timeband { get; set; }
[MaxLength(15)]
public string BtnNo { get; set; }
[MaxLength(20)]
public string AptName { get; set; }
[Index(IsUnique = true)]
public int GSMUnitId { get; set; }
public virtual GSMUnit GSMUnit { get; set; }
}
But I recommend you to take a look on Fluent API. It's easier to configure in my opinion.

Error in creating a controller file

I am using Entity Framework. I have tried everything, searching and adding keys but Ienter image description here cannot understand what the problem is and how to resolve it.
public class Reservation
{
[Key]
public int BookingID { get; set; }
public int CustomerID { get; set; }
public int RoomID { get; set; }
public string BookingDate { get; set; }
public int Check_In { get; set; }
public int Check_Out { get; set; }
public int Adults { get; set; }
public int Children { get; set; }
public int NoOfNights { get; set; }
[ForeignKey("RoomID")]
public virtual Room Rooms { get; set; }
[ForeignKey("CustomerID")]
public virtual CustomerDetails CustomerDetail { get; set; }
public virtual ICollection<Payment> Payment { get; set; }
}
public class CustomerDetails
{
[Key]
public int CustomerID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int PostCode { get; set; }
public string State { get; set; }
public int PhoneNumber { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public virtual ICollection<Reservation> Reservations { get; set; }
}
enter image description here
All tables need a primary key or you can't use Entity Framework.

Code first One way many to many relationship using data annotation

I have two models in my application: Stock and Report. A report can have many stocks and a stock can be used in many reports.
public enum ElectionType
{
MANAGER =1 ,
INSPECTOR ,
BOTH
}
public class Report
{
public Report()
{
Stocks = new List<Stock>();
}
public int ReportID { get; set; }
[Required]
public DateTime ShamsiDate { get; set; }
public int? StockID { get; set; }
[Required]
public ElectionType ElectionType { get; set; }
[ForeignKey("StockID")]
public virtual ICollection<Stock> Stocks { get; set;}
}
public class Stock
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int StockID { get; set; }
public int FinancialCode { get; set; }
public String NationalCode { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public String FatherName { get; set; }
public String Place { get; set; }
public int StockCount { get; set; }
public int StockPrice { get; set; }
public int StockSize { get; set; }
public int StartStock { get; set; }
public int EndStock { get; set; }
}
I want to create a one way relationship so there is no way to access a Report from a Stock. I have written this code but it doesn't work.
To do it with annotations you will need a junction table:
public class ReportStock
{
[Key, Column(Order = 1)]
public int ReportID { get; set; }
[Key, Column(Order = 2)]
public int StockID { get; set; }
[ForeignKey("ReportID")]
public virtual Report Report { get; set;}
[ForeignKey("StockID")]
public virtual Stock Stock { get; set;}
}
Then change your Report class:
public class Report
{
public Report()
{
ReportStocks = new List<ReportStock>();
}
public int ReportID { get; set; }
[Required]
public DateTime ShamsiDate { get; set; }
[Required]
public ElectionType ElectionType { get; set; }
public virtual ICollection<ReportStock> ReportStocks { get; set;}
}

Code First one to many relationship and category with parent category

public class Category
{
[Key]
public int CategoryId { get; set; }
public int ParentCategoryId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public int Status { get; set; }
public virtual ICollection<Category> ParentCategories { get; set; }
public virtual ICollection<ImageSet> ImageSets { get; set; }
[ForeignKey("ParentCategoryId")]
public virtual Category ParentCategory { get; set; }
}
public class ImageSet
{
[Key]
public int ImageSetId { get; set; }
public int CategoryId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string InsertDate { get; set; }
public int Status { get; set; }
public virtual ICollection<Image> Images { get; set; }
[ForeignKey("CategoryId")]
public virtual Category Category { get; set; }
}
public class Image
{
[Key]
public int ImageId { get; set; }
public int ImageSetId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string ImageUrl { get; set; }
public string ThumbImageUrl { get; set; }
public string InsertDate { get; set; }
public int Status { get; set; }
[ForeignKey("ImageSetId")]
public virtual ImageSet ImageSet { get; set; }
}
Context:
public DbSet<Category> Categories { get; set; }
public DbSet<Image> Images { get; set; }
public DbSet<ImageSet> ImageSets { get; set; }
error page:Introducing FOREIGN KEY constraint 'FK_dbo.ImageSets_dbo.Categories_CategoryId' on table 'ImageSets' may
cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or
ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could
not create constraint. See previous errors.
Whats the problem?
You need to add this:
modelBuilder.Entity<ImageSet>()
.HasRequired(is => is.Category)
.WithMany(c => c.ImageSets)
.WillCascadeOnDelete(false);
Here are good explanations of why this is happening :
https://stackoverflow.com/a/19390016/1845408
https://stackoverflow.com/a/17127512/1845408

how to get student courses with entity framework

I have 2 classes, course and student, and I want to get student courses with student id
help me please
I'm using entity framework code first
public class Course {
public int CourseID { get; set; }
public string Title { get; set; }
public string Details { get; set; }
public string img { get; set; }
public DateTime DateAdded { get; set; }
public Guid UserAddID { get; set; }
public Guid userEditID { get; set; }
public int SubCategoryID { get; set; }
public string Code { get; set; }
public string Summury { get; set; }
public decimal Price { get; set; }
public bool IsGift { get; set; }
public DateTime DateUpdated { get; set; }
public bool DelFlag { get; set; }
public DateTime? DelDate { get; set; }
public Guid? UserDelID { get; set; }
public ICollection<Student> Students { get; set; }
}
public class Student {
[Key]
public int StudentID { get; set; }
public string Name { get; set; }
public DateTime? DateBirth { get; set; }
public int? Age { get; set; }
public int? Sex { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
public string Mobile { get; set; }
public string Mobile2 { get; set; }
public string UniversityID { get; set; }
public string CollegeID { get; set; }
public string IdentityID { get; set; }
public string Address { get; set; }
public string Education { get; set; }
public decimal? Payments { get; set; }
public string HowToKnow { get; set; }
public DateTime? GradeDate { get; set; }
public string LaterCourses { get; set; }
public string Job { get; set; }
public string Specialist { get; set; }
public string Notes { get; set; }
public int StatueID { get; set; }
public Guid? UserID { get; set; }
public DateTime? DateAdded { get; set; }
public Guid UserAddID { get; set; }
public Guid userEditID { get; set; }
public DateTime DateUpdated { get; set; }
public bool DelFlag { get; set; }
public DateTime? DelDate { get; set; }
public Guid? UserDelID { get; set; }
public virtual IList<Course> Courses { get; set; }
}
I want to get all courses for a given StudentID using a lambda expression.
var students = repository.Query<Course>(c => c.Student.Any(st=>st.StudentID == StudentID)