I have two Models. A Bike, and Reservation.
Bike:
public class Bike
{
public int Id { get; set; }
public BikeType Type { get; set; }
public BikeGender Gender { get; set; }
public BikeSize Size { get; set; }
public string Brand { get; set; }
public double HourRate { get; set; }
public double DailyRate { get; set; }
public virtual Store Store { get; set; }
[ForeignKey("Store")]
public int Store_Id { get; set; }
}
and Reservation:
public class Reservation
{
public int Id { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
public virtual Customer Customer { get; set; }
[ForeignKey("Customer")]
public int Customer_Id { get; set; }
public virtual List<Bike> Bikes { get; set; }
public Reservation()
{
Bikes = new List<Bike>();
}
}
When I create the database from Code First it adds a column in the 'Bikes' table called: 'Reservation_Id'.
Click to view image of the problem
The problem comes when I create a new Reservation, The bike which I choose gets the 'Reservation_Id' of the Id from Reservation. So when I try to delete this Reservation I get an error:
SqlException: The DELETE statement conflicted with the REFERENCE
constraint "FK_dbo.Bikes_dbo.Reservations_Reservation_Id". The
conflict occurred in database "BikeRental.Model.BikeShopDataModel",
table "dbo.Bikes", column 'Reservation_Id'.
The code that I use to delete the reservation:
Click here to view the reservation delete code
How can I fix that I can just delete the reservation without interfering with the unique key? Or how do I delete the whole unique key from the table?
There is a One to Many relationship between Bike and Reservation.
EfCore or EF needs a ForeignKey on the Many side. When u did not define the ForeignKey on the rigth side, EF is gonna block you because that Reservation object dependent on the Bike object. Your mistake is defining that relationship in the wrong side.
Bike class should be like :
public class Bike
{
public int Id { get; set; }
public BikeType Type { get; set; }
public BikeGender Gender { get; set; }
public BikeSize Size { get; set; }
public string Brand { get; set; }
public double HourRate { get; set; }
public double DailyRate { get; set; }
public virtual Store Store { get; set; }
public List<Reservation> Reservations{get;set;}
[ForeignKey("Store")]
public int Store_Id { get; set; }
}
Reservation class should be like:
public class Reservation
{
public int Id { get; set; }
public DateTime Start { get; set; }
public DateTime End { get; set; }
public virtual Customer Customer { get; set; }
[ForeignKey("Customer")]
public int Customer_Id { get; set; }
public virtual Bike Bike { get; set; }
[ForeignKey("Bike")]
public int Bike_Id { get; set; }
}
Related
How can I make the foreign key of a table "PRODUCT" accept null values?
I require that at the time of filling the PRODUCT form you can save the information without having to select the bank. I generate the form PRODUCT(Controller) with entity framework
The foreign key del model Product -> "public int EntidadID { get; set; }"
I have two related models.
public class Product
{
[Key]
public int ProductID { get; set; }
public string NumContrato { get; set; }
public float TasaReal { get; set; }
public decimal Capital { get; set; }
public DateTime FechaValor { get; set; }
public DateTime FechaVencimiento { get; set; }
public int Plazo { get; set; }
public int BankID { get; set; }
public virtual CATbank CATbank { get; set; }
}
public class CATbank
{
[Key]
public int BankID { get; set; }
public string Name { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
Is BankID your foreign key?
If so, in the Product class try changing
public int BankID { get; set; }
to
public int? BankID { get; set; }
and in your database table make sure that the field is nullable.
A quick question for masters.
I got 2 EF model classes:
public class School
{
public int Id { get; set; }
[DisplayName("School")]
public string Name { get; set; }
public List<Teacher> Teachers { get; set; }
public List<Note> Notes { get; set; }
}
public class Teacher
{
public int Id { get; set; }
[DisplayName("Öğretmen")]
public string Name { get; set; }
public int SchoolId { get; set; }
public School School { get; set; }
public List<Note> Notes { get; set; }
}
Basically I want to create an one to many relationship in code-first.
But when I try to do that, I get this error:
Introducing FOREIGN KEY constraint 'FK_dbo.Teachers_dbo.Schools_SchoolId' on table 'Teachers' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Where have I made a mistake?
EDIT
public class Note
{
public int Id { get; set; }
[Required,DisplayName("Başlık"), StringLength(50)]
public string Title { get; set; }
[Required,DisplayName("Açıklama"), StringLength(4000)]
public string Description { get; set; }
public string File { get; set; }
public DateTime UploadDate { get; set; }
public bool IsApproved { get; set; }
public int SchoolId { get; set; }
public int OwnerId { get; set; }
public int TeacherId { get; set; }
//Keys
public School School { get; set; }
public Teacher Teacher { get; set; }
public List<Comment> Comments { get; set; }
}
I didnt get any error for this Model and Keys..
Remove the relationship from Note to School and vice versa. You could get the school by the teacher that has a relationship to the note.
It will produce your issue.
My data class is
public class Data
{
public int Id { get; set; }
public int LeagueId { get; set; }
public League League { get; set; }
public int HomeTeamId { get; set; }
public virtual Team HomeTeam { get; set; }
public int AwayTeamId { get; set; }
public virtual Team AwayTeam { get; set; }
}
and my team class is
public class Team
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Data> Datas { get; set; }
}
which generates an extra foreign key FK_dbo.Data_dbo.Teams_Team_Id and also and extra column in my Data table.
So my first question is, how that foreign-key was created there?
Can i have two one to many relationships that target at the same table with entity framework?
I need to set both the HomeTeamId and the AwayTeamId in the Data table as one to many relationship
Try:
public class Data
{
public int Id { get; set; }
public int LeagueId { get; set; }
[ForeignKey("LeagueId")] /* Add explicit foreign key data annotations */
public League League { get; set; }
public int HomeTeamId { get; set; }
[ForeignKey("HomeTeamId")]
public virtual Team HomeTeam { get; set; }
public int AwayTeamId { get; set; }
[ForeignKey("AwayTeamId")]
public virtual Team AwayTeam { get; set; }
}
public class Team
{
public Team()
{
this.HomeTeamData = new HashSet<Data>();
this.AwayTeamData = new HashSet<Data>();
}
public int Id { get; set; }
public string Name { get; set; }
[InverseProperty("HomeTeam")]
public virtual ICollection<Data> HomeTeamData { get; set; }
[InverseProperty("AwayTeam")]
public virtual ICollection<Data> AwayTeamData { get; set; }
}
Let me know if this helps.
I suspect you may be hitting the limit of Entity's ability to figure out what you want. You may need to consider using some Entity Annotations to instruct Entity on what you want it to actually do.
I am a VB.NET programmer, but I am trying to learn C# and MVC in my spare time. I am using ASP.NET MVC 5.1.0.0 and I am trying to do code-First database creation in a local instance of SQL Server.
I was able to get the first database table to update in the database when I ran Update-Database from within the IDE, but when I added a second table that has a PK/FK relationship with the first, I am getting a red line under [ForeignKey] which reads
Does not contain a constructor that takes 1 arguments
I have been searching all over and not getting anywhere. Any suggestions or help would be appreciated. By the way, the first table is a PK/FK relationship to the AspNetUsers table.
public class BuildDatabase : IdentityUser
{
public virtual Companies Companies { get; set; }
public virtual NotaryProfile NotaryProfile { get; set; }
}
public class Companies
{
[Key]
[Column("CompanyID")] // Did this as the database will reflect TableName_ColumnName instead.
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public bool IsActive { get; set; }
public bool IsNotary { get; set; }
public virtual ICollection<NotaryProfile> NotaryProfile { get; set; }
}
public class NotaryProfile
{
[Key]
public int NotaryID { get; set; }
public string NamePrefix { get; set; }
public string FirstName { get; set; }
public string MiddleInitial { get; set; }
public string LastName { get; set; }
public string NameSuffix { get; set; }
public bool IsActive { get; set; }
public int DefaultState { get; set; }
public int DefaultCounty { get; set; }
public bool IsSigningAgent { get; set; }
public bool HasABond { get; set; }
public decimal BondAmount { get; set; }
public bool HasEandO { get; set; }
public decimal EandOAmount { get; set; }
public bool ElectronicNotarizationsAllowed { get; set; }
public string ElectronicTechnologyUsed { get; set; }
public string ComissionNumber { get; set; }
public DateTime CommissionIssued { get; set; }
public DateTime CommssionOriginal { get; set; }
public DateTime CommissionExpires { get; set; }
public DateTime CommissionFiledOn { get; set; }
public string SOSAuditNumber { get; set; }
public string CommissionDesc { get; set; }
[Foreignkey("CompanyID")] // Companies.CompanyID = PK
public int CompanyID { get; set; } // PK/FK relationship.
public Companies Companies { get; set; } // Reference to Companies table above.
}
public class SchemaDBContext : IdentityDbContext<BuildDatabase>
{
public SchemaDBContext()
: base("DefaultConnection"){}
public DbSet<Companies> Companies { get; set; }
public DbSet<NotaryProfile> NotaryProfile { get; set; }
}
One of your classes (probably NotaryProfile) needs to reference another object (the foreign key relationship) but there is no constructor in that class that accepts an argument to establish that relationship, e.g.:
public NotaryProfile(int companyId) {
this.companyId = companyId;
}
BTW, a better way to establish that relationship is to use the actual class type rather than the ID, as in:
public class NotaryProfile {
...
public Company Company { get; set; }
// Instead of this:
// public int CompanyID { get; set; } // PK/FK relationship.
...
}
See also:
C# “does not contain a constructor that takes '1' arguments”
Does not contain a constructor that takes 2 arguments
I am using the code first approach, to create the database based on modals and the db context class. The problem is that when I create the relationships between one model and the next and run the code the data base generates foreign keys like it should.
How ever I want the relationships, with out the foreign keys. is this possible to do with entity framework and the code first approach?
for example:
namespace LocApp.Models
{
public class Location
{
public int id { get; set; }
[Required]
public string name { get; set; }
[Required]
public string address { get; set; }
[Required]
public string city { get; set; }
[Required]
public string country { get; set; }
[Required]
public string province { get; set; }
[Required]
public string phone { get; set; }
public string fax { get; set; }
public bool active { get; set; }
public virtual ICollection<LocationAssignment> LocationAssignment { get; set; }
}
}
Has a relationship with:
namespace LocApp.Models
{
public class LocationAssignment
{
public int id { get; set; }
public int locationID { get; set; }
public int serviceID { get; set; }
public int productID { get; set; }
public int personID { get; set; }
public virtual Location Location { get; set; }
public virtual Service Service { get; set; }
public virtual Product product { get; set; }
public virtual Person person { get; set; }
}
}
As you can see this table will have a foreign key generated with the location table. How do I keep this relationship WITH OUT the generation of foreign keys?
User Triggers On Insert and on update and delete relative and reference tables !!! but that's not cute you must control allthing in your application instead