I've got a table called Pages which has a primary Key of PageID. I want to use the following model to make at table called PageMap which gets the current and next PageID (one is going to be a link) but I keep getting an error with the foreign key. Any help would be greatly appreciated!
public class PageMap
{
public int PageMapID { get; set; }
[Required]
[DisplayName("Page Visible On")]
public int PageID { get; set; }
[Required]
[DisplayName("Question")]
public int QuestionID { get; set; }
[Required]
[ForeignKey("PageID")]
[DisplayName("Link to Page")]
public int NextPageID { get; set; }
[DisplayName("Ordering")]
public int Order { get; set; }
public virtual Pages Pages { get; set; }
public virtual Questions Questions { get; set; }
}
Try putting the name of the entity in foreign key attribute.i.e
[ForeignKey("Page")]
Related
I enabled Code First Migration but after sometime I changed the model properties so when i ran the application the following error is given.
Invalid column name etc...because after migration i changed the model.
So far I understand the problem is that I updated the model but these changes don't apply to database table...kindly help me to fix it..means model properties and database column don't match
Migration is enabled.
I set automatic migration to true but i doesn't work.
Error
public class Floor
{
public int FloorID { get; set; }
public string Name { get; set; }
public virtual ICollection<Room> Rooms { get; set;}
}
public class Room
{
public int RoomID { get; set; }
public string Name { get; set; }
[Display(Name ="Room Rent")]
public decimal Rent { get; set; }
[Display(Name="Floor")]
public int FloorID { get; set; }
public int Seater { get; set; }
[Display(Name="Attach Bathroom")]
public Boolean AttachedBathRoom { get; set; }
public virtual Floor Floor { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
public class Student
{
public int StudentID { get; set; }
public string Name { get; set; }
public int CNIC { get; set; }
public int Phone { get; set; }
[Display(Name="Floor")]
public int FloorID { get; set; }
[Display(Name ="Room No")]
public int RoomID { get; set; }
public string Address { get; set; }
public string Email { get; set; }
public string Department { get; set; }
public virtual Floor Floor { get; set; }
public virtual Room Room { get; set; }
}
First, you need to specify your primary and foreign keys in your classes.
To specify a primary key, add [Key] before your key attribute. For a foreign key, you also have to add the table it is linked to. So in your Room class you would have something like this:
[Key]
[ForeignKey("Floor")]
public int FloorID { get; set; }
Do the same for all your keys in all your models.
Then, you need to add a new migration and then update your database.
In your Packet Manager Console, type this to add a new migration:
Add-Migration FooBar
Then update your database with this command:
Update-Database
I'm using VS 2010 with Razor/MVC 3 to create a form where User 1 submits information to a database using RequestQueue Model (this is just a queue table). User 2 then pulls this information, approves it, and the data is sent to the main database via DbRequestForm Model. This model, however, consists of several sub-models (Data_Dictionary, SERVER_DATABASE, and DatabaseRequestInfo) because the submitted data needs to go to three separate tables.
The problems is, whenever I approve the data for submission from RequestQueue to DbRequestForm, I get an error saying there is no primary key for DbRequestForm. However, there is a PK for each sub-model. I have also tried adding [Key] public int SrvrDB_ID { get; set; } and other variations to DbRequestForm to no avail.
Initial Model:
public class RequestQueue
{
[Key]
public int SrvrDB_ID { get; set; }
public string dbName { get; set; }
public int InitialSpaceNeeded { get; set; }
public string ScheduledJobSetup { get; set; }
public string PII_data { get; set; }
}
Encapsulating Model:
public class DbRequestForm
{
public Data_Dictionary Data_Dictionary { get; set; }
public DatabaseRequestInfo DatabaseRequestInfo { get; set; }
public SERVER_DATABASE SERVER_DATABASE { get; set; }
}
Models based on final three tables:
public class Data_Dictionary
{
[Key]
public int SrvrDB_ID { get; set; }
public string PII_data { get; set; }
}
public class SERVER_DATABASE
{
[Key]
public int SrvrDB_ID { get; set; }
public string dbName { get; set; }
}
public class DatabaseRequestInfo
{
[Key]
public int SrvrDB_ID { get; set; }
public int InitialSpaceNeeded { get; set; }
public string ScheduledJobSetup { get; set; }
}
Any ideas how to avoid this error? Thanks in advance!
EDIT: The specific error is '
System.Data.Edm.EdmEntityType: : EntityType 'DbRequestForm' has no key
defined. Define the key for this EntityType.
System.Data.Edm.EdmEntitySet: EntityType: EntitySet DbRequestForms is
based on type DbRequestForm that has no keys '
The error tells that you need to define key for DBRequestForm.
Code First would infer that a property is a primary key if the property is called ‘Id’ or ‘class name Id’.
In your case you have to add
[Key]
public int DBRequestFormId { get; set; }
This concrete error won't appear anymore.
here is detailed information how code first works
http://blogs.msdn.com/b/efdesign/archive/2010/06/01/conventions-for-code-first.aspx
see the Primary Key section
I have the following model for an article.
public class Article
{
[Key]
public int ArticleId { get; set; }
[Required(ErrorMessage = "Title is required."), MaxLength(80)]
public string Title { get; set; }
[Required(ErrorMessage = "Body is required.")]
public string Body { get; set; }
public DateTime Time { get; set; }
public int AuthorId { get; set; }
// Navigation properties
public virtual UserProfile Author { get; set; }
public virtual ICollection<Tag> Tags { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
The UserProfile is an extendend version of the default in the MVC4 standard project.
Now, in my scaffolded controller/view, there is no way to enter the Author.
My database (MySQL) contains a field with named Author_UserId of type int.
What is wrong?
Also, is it really necessary for the author to be referenced both via the navigation property and the AuthorId
It's not common to use 2 the same Foreign keys of a specific table at any table. Such this interpreted as data redundancy. To solve the problem without any redundancy, i suggest bellow model to you:
public class Article
{
[Key]
public int ArticleId { get; set; }
[Required(ErrorMessage = "Title is required."), MaxLength(80)]
public string Title { get; set; }
[Required(ErrorMessage = "Body is required.")]
public string Body { get; set; }
public DateTime Time { get; set; }
public int AuthorId { get; set; }//determine name of foreign key here of type primary key of navigatable table
// Navigation properties
[ForeignKey("AuthorId")]
public virtual UserProfile Author { get; set; }//column with name 'AuthorId'
public virtual ICollection<Tag> Tags { get; set; }
public virtual ICollection<Comment> Comments { get; set; }
}
Solution above, used to self naming navigation property foreign key.
I wish be useful.
I'm experimenting with Entity Framework 4 Code First.
I have my (simplified) models set up like this.
public class Entry
{
public int Id { get; set; }
[Required]
public virtual EntryTag Tag { get; set; }
[Required]
public int TagId { get; set; }
[Required]
public string UserId { get; set; }
}
public class EntryTag
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Color { get; set; }
[Required]
public string UserId { get; set; }
}
The user can create a new Entry, and in the same time create or re-use an EntryTag. I try to find an already existing EntryTag based on the name and userId.
var tag = ResolveTag(entry.Tag.Name, entry.UserId);
entry.Tag = tag == null ? AddTagBasedOn(entry) : tag;
_entryRepository.Add(entry);
Now when I find an existing EntryTag, I set it to the Tag property of the Entry. But instead of reusing the EntryTag, the EntryTag gets added (!). I hoped EF would just use the Id to fill in the foreign key? Or am I missing a convention/configuration here?
Thanks
I am working with the EF Code First library trying to work on an appointment scheduling app.
The model's I have are going to be a Client, Appointment, and AppointmentType...
Basically each Client can have a set of Appointments, and each Appointment can have a single AppointmentType...
The code is as follows:
public class Client
{
[ScaffoldColumn(false)]
public int ClientID { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[EmailAddress]
[Required]
public string Email { get; set; }
[DataType("DateTime")]
public DateTime Birthday { get; set; }
[Required]
public string CellPhone { get; set; }
public string HomePhone { get; set; }
public string Notes { get; set; }
public virtual ICollection<Appointment> Appointments{ get; set; }
public string Name {
get{
return FirstName + " " + LastName;
}
}
public class Appointment
{
[ScaffoldColumn(false)]
public int AppointmentID { get; set; }
[ScaffoldColumn(false)]
public int ClientID { get; set; }
[ScaffoldColumn(false)]
public int AppointmentTypeID { get; set; }
[Required]
public DateTime AppointmentDate { get; set; }
public string Notes { get; set; }
public virtual AppointmentType AppointmentType { get; set; }
public virtual Client Client { get; set; }
}
public class AppointmentType
{
[ScaffoldColumn(false)]
public int AppointmentTypeID { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
public virtual Appointment Appointment { get; set; }
}
Everything works well when I create an appointment type, and a client, but when I create an appointment I get the following error...
InnerException {"The INSERT statement conflicted with the FOREIGN KEY constraint \"Appointment_Client\". The conflict occurred in database \"Salon.Models.SalonContext\", table \"dbo.Clients\", column 'ClientID'.\r\nThe statement has been terminated."} System.Exception {System.Data.SqlClient.SqlException}
If more details are needed, please let me know...I am just trying to figure out if I am missing anything in the setup.
This is what happens when I debug on the post to create the Appointment...All the ID's are as 0 which is correct, but should the other fields not be null?? Or does it matter...Just not very familiar with how things should look this being my first EF Code First project...
According to your setup, one AppointmentType can only have one Appointment. This is a one-to-one mapping. In this case, you better move the AppointmentType into the Appointment entity. Otherwise, what I believe is more logical, an AppoitmentType can have many Appointments but one Appointment can have only one AppointmentType. Accordingly, you should have a virtual ICollection inside your AppointmentType entity.
public class AppointmentType
{
[ScaffoldColumn(false)]
public int AppointmentTypeID { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
public virtual ICollection<Appointment> Appointments { get; set; }
}
I am not sure this is what's causing the problem but it could be. Sometimes mapping faults cause some weird exceptions to be thrown. Give it a try and let me know if your problem gets resolved.
By your constraints AppointmentType and Client cannot be null in Appointment. You can delete constraints or set correct objects in object properties. For example create Client and AppointmentType and then create Appointment for created Client with created AppointmentType