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.
Related
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; }
}
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 using models to define my tables using EF code-first.
I have and Item model and an Order model.
Item:
public class Item
{
public int ItemID { get; set; }
[Required]
public int Price { get; set; }
[Required]
public int AmountLeft { get; set; }
[Required]
public string Image { get; set; }
[Required]
public string Description { get; set; }
[Required]
public string FullDescription { get; set; }
[Required]
public DateTime PublishDate { get; set; }
public int CompanyID { get; set; }
public int CategoryID { get; set; }
// Navigation properties
public virtual Company Company { get; set; }
// Navigation properties
public virtual Category Category { get; set; }
}
Order model:
public class Order
{
public int OrderID { get; set; }
[Required]
public DateTime DeliveryDate { get; set; }
[Required]
public string Currency { get; set; }
[Required]
public int TotalAmount { get; set; }
public List<int> Items { get; set; }
public DateTime OrderDate { get; set; }
public int UserID { get; set; }
// Navigation properties
public virtual User user { get; set; }
}
I want to create another table which will be called ItemInOrder which will only have 2 fields: ItemID and OrderID.
the primary key would be these 2 foreign keys.
i tried to define this model:
public class ItemInOrder
{
public int OrderID { get; set; }
public int ItemID { get; set; }
// Navigation properties
public virtual Order order { get; set; }
public virtual Item item { get; set; }
}
But i got errors. i tried to put [Key] notation on both fields but still i got errors.
how will i be able to create the table i want?
When you need to create a table with composite PKs, you need to specify the order of you keys. There are two variants:
You could override the OnModelCreating method on your Context, and try with these Fluent Api configurations:
// Configure the primary keys for the ItemInOrder in the order you want
modelBuilder.Entity<ItemInOrder>()
.HasKey(t => new{t.OrderID,ItemID);
modelBuilder.Entity<ItemInOrder>()
.HasRequired(io=>io.Order)
.WithMany()
.HasForeigKey(io=>io.OrderID);
modelBuilder.Entity<ItemInOrder>()
.HasRequired(io=>io.Item)
.WithMany()
.HasForeigKey(io=>io.ItemID);
The second variant using Data Annotations should be this way:
[Key]
[Column(Order=1)]
[ForeignKey("Order")]
public int OrderID { get; set; }
[Key]
[Column(Order=2)]
[ForeignKey("Item")]
public int ItemID { get; set; }
EF will notice you want to create two relationships and it will do the job for you.
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