3 table relationship - c#

I'm trying to estabilish relationship between 3 tables in c#
My models are:
Guitar:
public class Guitar
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public int Id { get; set; }
[MaxLength(30)]
[Required]
public string Model { get; set; }
public int? Price { get; set; }
[NotMapped]
public virtual Brand Brand { get; set; }
public int BrandId { get; set; }
Brand:
public class Brand
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[NotMapped]
public virtual ICollection<Guitar> Guitars { get; set; }
public Brand()
{
Guitars = new HashSet<Guitar>();
}
Purchase:(Some properties might be missing here)
public class Purchase
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public int Id { get; set; }
[Required]
[MaxLength(40)]
public string BuyerName { get; set; }
[NotMapped]
public virtual Guitar Guitar { get; set; }
public int GuitarId { get; set; }
}
I've managed to link the guitar and the brand tables together, but I can't deal with the third one.
Here's my code so far:
modelBuilder.Entity<Guitar>(entity =>
{
entity.HasOne(guitar => guitar.Brand)
.WithMany(brand => brand.Guitars)
.HasForeignKey(guitar => guitar.BrandId)
.OnDelete(DeleteBehavior.ClientSetNull);
});
Foreign key in Purchases table should be the ID of the guitar, but if you have a better idea I'm open to it.
So, how do I do the same with the Purchases?

remove all [NotMapped] from your classes, And I would add a Buyer class too
public class Guitar
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public int Id { get; set; }
....
[Required]
public int? BrandId { get; set; }
public virtual Brand Brand { get; set; }
}
public class Brand
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public int Id { get; set; }
.....
public virtual ICollection<Guitar> Guitars { get; set; }
public Brand()
{
Guitars = new HashSet<Guitar>();
}
}
public class Buyer
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public int Id { get; set; }
[Required]
[MaxLength(40)]
public string Name { get; set; }
public virtual ICollection<Purchase> Purchases { get; set; }
public Bayer()
{
Purchases = new HashSet<Purchase>();
}
}
public class Purchase
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Required]
public int Id { get; set; }
[Required]
public int? BuyerId { get; set; }
public virtual Buyer Buyer { get; set; }
[Required]
public int? GuitarId { get; set; }
public virtual Guitar Guitar { get; set; }
}
and if your are using net core 5+ you don't need any fluent apis

Related

One to many relationship crud

I am currently working with Asp.NEt Core 6. I would like to create CRUD with one to many relationship between two Models (Staffs and Tax). The idea is to have one staff have several tax entries.
Staff Model
namespace Join.Models
{
public class Staff
{
[Key]
public int staffid { get; set; }
public string staffname { get; set; }
public int salary { get; set; }
}
}
Tax Model
namespace Join.Models
{
public class Paye
{
public int Id { get; set; }
[DataType(DataType.Date)]
public DateTime CreatedDate { get; set; }
public int amount { get; set; }
[Required]
[ForeignKey("Staff")]
public int staffid { get; set; }
public virtual Staff Staff { get; set; }
}
}
I do not know how to code the controllers and views
I think it should be like this:
namespace Join.Models
{
public class Staff
{
[Key]
public int staffid { get; set; }
public string staffname { get; set; }
public int salary { get; set; }
public virtual List<Paye> taxEntries {get; set; }
}
}
namespace Join.Models
{
public class Paye
{
public int Id { get; set; }
[DataType(DataType.Date)]
public DateTime CreatedDate { get; set; }
public int amount { get; set; }
[Required]
public int staffid { get; set; }
[ForeignKey("staffid")]
public virtual Staff Staff { get; set; }
}
}
And i would recommend you make a migration after these changes

How to effectively implement 1 to many relationship?

I have an EF model to is connected 1 to 1 for many tables but I am having trouble connecting a 1 to many table. Currently using EF6 on .Net 4.8. The error I am recieving is "Multiplicity is not valid in Role '' in relationship 'Login_Users'. Because the Dependent Role refers to the key properties, the upper bound of the multiplicity of the Dependent Role must be '1'"
The main table is
Users
public partial class Users
{
public Users()
{
this.Login = new HashSet<Login>();
this.Phone = new HashSet<Phone>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public System.DateTime BirthDate { get; set; }
public int LastFourSSN { get; set; }
public Nullable<int> AddressId { get; set; }
public virtual Address Address { get; set; }
public virtual ICollection<Login> Login { get; set; }
public virtual ICollection<Phone> Phone { get; set; }
}
One to one tables
public partial class Login
{
public Login()
{
this.Login_Track = new HashSet<Login_Track>();
this.Policy = new HashSet<Policy>();
}
public string Username { get; set; }
public string Password { get; set; }
[Key, ForeignKey("Users")]
public Nullable<int> UserId { get; set; }
public System.DateTime CreationDate { get; set; }
public Nullable<System.DateTime> LastLoginDate { get; set; }
public virtual Users Users { get; set; }
}
Address
public partial class Address
{
public Address()
{
this.Users = new HashSet<Users>();
}
[Key, ForeignKey("Users")]
public int Id { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string City { get; set; }
public string County { get; set; }
public string State { get; set; }
public string PostalCode { get; set; }
public virtual ICollection<Users> Users { get; set; }
}
1 to many table
public partial class Phone
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Number { get; set; }
public string Type { get; set; }
[ForeignKey("Users")]
public Nullable<int> UserId { get; set; }
public virtual Users Users { get; set; }
}

Entity Framework Relationships two tables

I'm trying to create a Friendship mapping table that has 2 FK's that originate from the same class (User and SportsFacility)
Here are my model classes.
public partial class User
{
[Key]
public int Id { get; set; }
[Required]
public int AcountId { get; set; }
[Required]
[MaxLength(20)]
//[Column(TypeName = "varchar")]
public string Login { get; set; }
[Required]
[MaxLength(20)]
public string Name { get; set; }
[Required]
public string Password { get; set; }
public virtual ICollection<CheckQueue> ChecksQueue { get; set; }
public virtual ICollection<BookedEvent> BookedEvents { get; set; }
}
public partial class SportsFacility
{
public SportsFacility()
{
ChecksQueue = new List<CheckQueue>();
BookedEvent = new List<BookedEvent>();
}
[Key]
public int Id { get; set; }
[Required]
[MaxLength(30)]
public string Name { get; set; }
[Required]
public int PnH_Id { get; set; }
[Required]
[MaxLength(70)]
public string Address { get; set; }
public int City_Id { get; set; }
[ForeignKey("City_Id")]
public virtual City City { get; set; }
public virtual ICollection<CheckQueue> ChecksQueue { get; set; }
public virtual ICollection<BookedEvent> BookedEvent { get; set; }
}
public partial class CheckQueue
{
[Key]
public int Id { get; set; }
public DateTime StartCheckTime { get; set; }
[Required]
public string CheckParams { get; set; }
public string Error { get; set; }
public bool IsDeleted { get; set; }
public int User_Id { get; set; }
[ForeignKey("User_Id")]
public virtual User User { get; set; }
public int SportsFacility_Id { get; set; }
[ForeignKey("SportsFacility_Id")]
public virtual SportsFacility SportsFacility { get; set; }
[Index]
public DateTime? LastCheck { get; set; }
}
public partial class BookedEvent
{
[Key]
public int Id { get; set; }
public DateTime BookDate { get; set; }
[Required]
public string CheckParams { get; set; }
public string Error { get; set; }
public bool IsDeleted { get; set; }
public int User_Id { get; set; }
[ForeignKey("User_Id")]
public virtual User User { get; set; }
public int SportsFacility_Id { get; set; }
[ForeignKey("SportsFacility_Id")]
public virtual SportsFacility SportsFacility { get; set; }
}
I tried override the OnModelCreating method in the DbContext:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<City>();
modelBuilder.Entity<SportsFacility>();
modelBuilder.Entity<User>();
modelBuilder.Entity<CheckQueue>();
modelBuilder.Entity<BookedEvent>();
base.OnModelCreating(modelBuilder);
}
This causes a new error message to be displayed.
Additional information: The entity types 'BookedEvent' and 'CheckQueue' cannot share table 'CheckQueues' because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary keys between them.
Any help would be greatly appreciated.

Multiplicity in Entity Framework

I'm new to Entity Framework and I've run into some problems while trying to implement my ERD Code First. The situation is as follows:
ERD
A product has a group of questions (QuestionGroup). A QuestionGroup has multiple questions and can belong to multiple Questionaires. A Questionaire basically has a questiongroup and a questionorder. The questionorder is supposed to keep the position of a question within that questionaire. The Questionaire table is needed because a QuestionGroup can have multiple questionorders, and a questionorder can belong to multiple questiongroups.
Because I'm trying my best to keep this post succinct I won't post all my classes, unless you ask to see them. The Entity classes I've made look like this:
public class Question
{
[Key]
public int Id { get; set; }
[MaxLength(2000)]
[Required]
public string Text { get; set; }
public Answer Answer { get; set; }
public QuestionType Type { get; set; }
public ICollection<QuestionAnswerOption> Options { get; set; }
public ICollection<QuestionOrder> Orders { get; set; }
[ForeignKey("FollowupQuestion")]
public int QuestionId { get; set; }
public virtual Question FollowupQuestion { get; set; }
[ForeignKey("Questiongroup")]
public int QuestionGroupId { get; set; }
public virtual QuestionGroup Questiongroup { get; set; }
}
public class QuestionOrder
{
[Key]
public int Id { get; set; }
public int Position { get; set; }
[ForeignKey("Question")]
[Required]
public int QuestionId { get; set; }
public virtual Question Question { get; set; }
[ForeignKey("Questionaire")]
[Required]
public int QuestionaireId { get; set; }
public virtual Questionaire Questionaire { get; set; }
}
public class Product
{
[Key]
public int Id { get; set; }
[MaxLength(150)]
[Required]
[Index(IsUnique = true)]
public string Name { get; set; }
[MaxLength(500)]
public string Summary { get; set; }
[MaxLength(500)]
public string Examples { get; set; }
public virtual QuestionGroup QuestionGroup { get; set; }
}
public class QuestionGroup
{
[Key]
public int Id { get; set; }
public ICollection<Question> Questions { get; set; }
[ForeignKey("Product")]
public int ProductId { get; set; }
public virtual Product Product { get; set; }
}
public class Questionaire
{
[Key]
public int Id { get; set; }
public QuestionGroup Group { get; set; }
public QuestionOrder Order { get; set; }
}
The errors I'm getting look like this:
QuestionGroup_Product_Source: : Multiplicity is not valid in Role 'QuestionGroup_Product_Source' in relationship 'QuestionGroup_Product'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
QuestionOrder_Questionaire_Source: : Multiplicity is not valid in Role 'QuestionOrder_Questionaire_Source' in relationship 'QuestionOrder_Questionaire'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
QuestionType_Question_Source: : Multiplicity is not valid in Role 'QuestionType_Question_Source' in relationship 'QuestionType_Question'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
The question we've arrived at here is:
Does anyone here know of a way to fix the relations between my tables? Maybe my ERD needs some improvements too, but I think the problem is that I'm missing a few things with my Code First implementation.
what about this design for you;)
public class Customer
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int CustomerId { get; set; }
public string CompanyName { get; set; }
public virtual ICollection<ContactInfo> ContactInfoes { get; set; }
public virtual ICollection<ProductQuestionaireReport> Reports { get; set; }
}
public class ContactInfo
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Key]
public int ContactInfoId { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public int Telephone { get; set; }
[ForeignKey("Customer")]
public int CustomerId { get; set; }
public virtual Customer Customer { get; set; }
}
public class ProductQuestionaireReport
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ProductQuestionaireReportId { get; set; }
[ForeignKey("Product")]
public int ProductId { get; set; }
public virtual Product Product { get; set; }
public virtual QuestionaireResult Result { get; set; }
[ForeignKey("Customer")]
public int CustomerId { get; set; }
public virtual Customer Customer { get; set; }
public bool Haste { get; set; }
public string Status { get; set; }
public string Comment { get; set; }
}
public class QuestionaireResult
{
[Key, ForeignKey("ProductQuestionaireReport")]
public int ProductQuestionaireReportId { get; set; }
[ForeignKey("Questionaire")]
public int QuestionaireId { get; set; }
public virtual Questionaire Questionaire { get; set; }
public DateTime SurveyCreated { get; set; }
public Double Costs { get; set; }
public Double FunctionPoints { get; set; }
public virtual ProductQuestionaireReport ProductQuestionaireReport { get; set; }
public virtual ICollection<QuestionaireAnswer> Answers { get; set; }
}
public class Product
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ProductId { get; set; }
public string Name { get; set; }
public string Summary { get; set; }
public string Examples { get; set; }
public virtual ICollection<Questionaire> Questionaires { get; set; }
public virtual ICollection<ProductQuestionaireReport> Reports { get; set; }
}
public class QuestionaireAnswer
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int QuestionaireAnswerId { get; set; }
[ForeignKey("QuestionaireResult")]
public int QuestionaireResultId { get; set; }
public virtual QuestionaireResult QuestionaireResult { get; set; }
[ForeignKey("QuestionaireQuestion")]
public int QuestionaireId { get; set; }
public virtual QuestionaireQuestion QuestionaireQuestion { get; set; }
[ForeignKey("Answer")]
public int AnswerId { get; set; }
public virtual QuestionOption Answer { get; set; }
public string Text { get; set; }
public virtual ICollection<string> Files { get; set; }
}
public class Questionaire
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int QuestionaireId { get; set; }
[ForeignKey("Product")]
public int ProductId { get; set; }
public virtual Product Product { get; set; }
public virtual ICollection<QuestionaireQuestion> QuestionaireQuestions { get; set; }
public virtual ICollection<QuestionaireResult> Results { get; set; }
}
public class Question
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int QuestionId { get; set; }
[ForeignKey("ParentQuestion")]
public int ParentQuestionId { get; set; }
public virtual Question ParentQuestion { get; set; }
public virtual QuestionType QuestionType { get; set; }
public virtual ICollection<QuestionOption> Options { get; set; }
}
public class QuestionType
{
[Key, ForeignKey("Question")]
public int QuestionId { get; set; }
public string Text { get; set; }
public bool IsOpenQuestion { get; set; }
public virtual Question Question { get; set; }
}
public class QuestionOption
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int QuestionAnswerOptionId { get; set; }
[ForeignKey("Question")]
public int QuestionId { get; set; }
public string Text { get; set; }
public virtual Question Question { get; set; }
}
public class QuestionaireQuestion
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int QuestionaireQuestionId { get; set; }
[ForeignKey("Questionaire")]
public int QuestionaireId { get; set; }
public virtual Questionaire Questionaire { get; set; }
[ForeignKey("Question")]
public int QuestionId { get; set; }
public int DisplayOrder { get; set; }
public virtual Question Question { get; set; }
}
also you must add this to OnModelCreating
modelBuilder.Entity<Customer>().HasMany(c => c.ContactInfoes)
.WithRequired(i => i.Customer).HasForeignKey(i => i.CustomerId).WillCascadeOnDelete(false);
modelBuilder.Entity<Question>().HasMany(q => q.Options)
.WithRequired(o => o.Question).HasForeignKey(o => o.QuestionId).WillCascadeOnDelete(false);
modelBuilder.Entity<QuestionaireResult>().HasMany(r => r.Answers)
.WithRequired(a => a.QuestionaireResult).HasForeignKey(o => o.QuestionaireResultId).WillCascadeOnDelete(false);
check it and feedback me ...

ForeignKey as Required in EntityFramework Code First

I'm working with code first for a ecommerce project,
I have 2 classes: Category and Products
Relationship is one to many, Category has many products,
I want to make the foreign key as required (not null) so, if I add a product, I must enter the categoryid.
When I do so, I get this error:
Introducing FOREIGN KEY constraint 'FK_dbo.Products_dbo.Categories_categoryId' on table 'Products' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Any ideas?
public class Category :IObjectWithState
{
[Key]
public int CategoryId { get; set; }
[Required]
public string Discription { get; set; }
public string Notes { get; set; }
public int ParentCategoryId { get; set; }
public virtual ICollection<Product> Products { get; set; }
public virtual ICollection<Discount> Discounts { get; set; }
public virtual ICollection<ProductList> ProductLists { get; set; }
[NotMapped]
public State state { get; set; }
}
public class Product :IObjectWithState
{
[Key]
public int ProductId { get; set; }
[Required]
public string ProductName { get; set; }
[Required]
public string ShortDiscription { get; set; }
public string LongDiscription { get; set; }
[Required]
public bool Active { get; set; }
[Required]
public int categoryId { get; set; }
[ForeignKey("categoryId")]
public Category Category { get; set; }
public ICollection<ProductImage> ProductImage { get; set; }
public ICollection<Discount> Discount { get; set; }
public ICollection<Discussion> Duscussion { get; set; }
public ICollection<ProductAttributeValue> ProductAttributeValue { get; set; }
public ICollection<ProductListItem> ProductListItem { get; set; }
public ICollection<ProductSKU> ProductSKU { get; set; }
public ICollection<RelatedProduct> RelatedProduct { get; set; }
public ICollection<Review> Review { get; set; }
public ICollection<ShoppingCart> ShoppingCart { get; set; }
}
i set cascadeDelete: to false in the Migration class

Categories

Resources