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
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 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.
Am building tender board Application am getting some confusing in how structure my model using >> entity-framework in >> MVC4
Here the descriptions:
In my simple membership Role Table , I have:
(Admin,Tender,Provider,Member)
Administration: he have right to change normal user role from “Member” to “Provider and prove winner bidder after tender organization approved.
Suppliers: Normal users will be assigning as “member” and will be activated by Administration to be provider and then they can bid any projects they want.
Projects: created by Tender Organization Users every project has many requirements
Requirement: each one related to project.
Tenders: Here my problem actually Tender are “Ministries in country and have to be set in system” but each ministry obvious have many users “Manager, let say 5 in each” who will vote for supplier.Mangers can vote to only those suppliers which are laid under the same ministry.
Do I miss others tables?
Also I don’t really know how to structure all the tables with relations and also with (UserprofileTbale, and Role Table):
Here my try, help me on that.
My DBContext:
public class ProjectContext : DbContext
{
public ProjectContext()
: base("OTMSProjects")
{
}
public DbSet<ProjectEntry> Entries { get; set; }
public DbSet<Requiernments> RequiernmentEntries { get; set; }
public DbSet<Supplier> Suppliers { get; set; }
public DbSet<Tender> Tenders { get; set; }
public DbSet<UserProfile> UserProfiles { get; set; }
//public DbSet<UserRoles> UserRoles { get; set; } // do I have to set this too?
}}
My tables:
public class ProjectEntry
{
[Key]
public int ID { get; set; }
[Required]
public string ProjectName { get; set; }
public string Description { get; set; }
public string Statue {get; set; }
public string UplodedFiles { get; set; }
public string Budget { get; set; }
public string EstimateTime { get; set; }
public string Criterias { get; set; }
public DateTime? DueDate { get; set; }
// Relations with others tables
public virtual Tender Tender { get; set; }// every project have only one tender
public virtual ICollection<Supplier> Suppliers { get; set; } // every project have one or more supplier
public virtual ICollection<Requiernments> Requirements { get; set; }
}
........
public class Requiernments
{
[Key]
public int RequiernmentId { get; set; }
public int ID { get; set; }
public string RequiernmentName { get; set; }
public string RequiernmentType { get; set; }
public string RequiernmentPrioritet { get; set; }
public float RequiernmenWhight { get; set; }
public string ProviderAnswer { get; set; }
public string ProviderComments{ get; set; }
public virtual ProjectEntry Projects { get; set; }
}
........
public class Supplier
{
[Key]
public int SupplierId { get; set; }
public int ID { get; set; }
public int SupplierName { get; set; }
public int SupplierCat { get; set; }
public virtual ICollection<ProjectEntry> Projects { get; set; }
}
......
public class Tender
{
[Key]
public int TenderId { get; set; }
public string TenderName { get; set; }
public string TenderMinstry{ get; set; }
public int ID { get; set; }//link to project
public int UserId { get; set; } //this links to the userid in the UserProfiles table
public virtual ICollection<ProjectEntry> Projects { get; set; }
//public virtual ICollection<UserProfile> Userprofile { get; set; }
public virtual UserProfile UserProfile { get; set; }
}
My membership table in my AccountModel created by defualt in Mvc4 ( I only add the RoleTable :
[Table("UserProfile")]
public class UserProfile
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string EmailAddress { get; set; }
public ICollection<UserRoles> UserRoles { get; set; }
}
[Table("webpages_Roles")]
public class UserRoles
{
[Key]
public int RoleId { get; set; }
public string RoleName { get; set; }
[ForeignKey("UserId")]
public ICollection<UserProfile> UserProfiles { get; set; }
}
Am not sure also about how to link the Userprofile with Tender Table and supplier Table?
Not sure what you are missed or not. but as per database creation you must follow your business logic and normalization rules.
Some of my suggestions are here:
1. ProjectEntry
here you should create a Status Table separately and gives its reference key as StatusID into the ProjectEntry table.
Requirement
you should create Requirement Priority and Type tables are separately.
Add separate table for provider question and answers. I hope you need to store more than one question answers for single requirement.
Supplier
Add Separate Table for Supplier category
Tender
Create Tender Ministry table separately and give its reference to the tender table.
you should make a table for Uploaded files as Documents. It should contains ID, ProjectId, Documentname, DocumentType, DocumentShortDescription, uplodatedDateTime fields.