I'm attempting to use migrations to generate my EF database, but I'm getting a couple of errors when I'm executing the update-database command.
Error 1
Failed executing DbCommand (7ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [Occupier] (
[OccupierId] int NOT NULL IDENTITY,
[Title] int NOT NULL,
[FirstName] nvarchar(32) NULL,
[LastName] nvarchar(32) NULL,
[Dob] datetime2 NOT NULL,
[Relationship] nvarchar(32) NULL,
CONSTRAINT [PK_Occupier] PRIMARY KEY ([OccupierId]),
CONSTRAINT [FK_Occupier_Property_OccupierId] FOREIGN KEY ([OccupierId]) REFERENCES [Property] ([PropertyId]) ON DELETE CASCADE
);
Error 2
Cascading foreign key 'FK_Occupier_Property_OccupierId' cannot be created where the referencing column 'Occupier.OccupierId' is an identity column.
Could not create constraint or index. See previous errors.
From what I can see I have my tables set up correctly, but there's obviously something missing which I can't see. I'll post the code for the tables below and hopefully someone can see what I'm missing.
For clarity; a SolicitorInstruction has a Property object, which may contain a number of Occupiers.
I'm also not sure about the way [ForeignKey("string")] works. Is this saying "this is a foreign key to primary key "string"? or "string" is a foreign key?
SolicitorInstruction
public class SolicitorInstruction
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SolicitorInstructionId { get; set; }
public InstructionTypes InstructionType { get; set; }
public int ApplicationId { get; set; }
public DateTime DateLogged { get; set; }
[ForeignKey("AdditionalInformationId")]
public AdditionalInformation AdditionalInformation { get; set; }
[ForeignKey("BorrowerBankId")]
public BorrowerBank BorrowerBank { get; set; }
[ForeignKey("BrokerId")]
public Broker Broker { get; set; }
[ForeignKey("PropertyId")]
public Property Property { get; set; }
[ForeignKey("SolicitorId")]
public Solicitor Solicitor { get; set; }
[ForeignKey("BorrowerId")]
public List<Borrower> Borrower { get; set; }
[ForeignKey("CurrentLenderId")]
public List<CurrentLender> CurrentLender { get; set; }
}
Property
[Table("Property")]
public partial class Property
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PropertyId { get; set; }
[StringLength(8)]
public string ReferenceNumber { get; set; }
[StringLength(4)]
public string CaseOwner { get; set; }
public int AmountBorrowed { get; set; }
[ForeignKey("SecurityAddressId")]
public Address Security { get; set; }
[ForeignKey("CorrespondenceAddressId")]
public Address Correspondence { get; set; }
[ForeignKey("OccupierId")]
public List<Occupier> Occupier { get; set; }
public TenureTypes Tenure { get; set; }
public JurisdictionTypes Jurisdiction { get; set; }
public FunderTypes Funder { get; set; }
public Property()
{
Occupier = new List<Occupier>();
}
}
Occupier
[Table("Occupier")]
public partial class Occupier
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int OccupierId { get; set; }
public Honorifics Title { get; set; }
[StringLength(32)]
public string FirstName { get; set; }
[StringLength(32)]
public string LastName { get; set; }
public DateTime Dob { get; set; }
[StringLength(32)]
public string Relationship { get; set; }
}
Try this changes to add the navigation property in the dependent class.
Property
[Table("Property")]
public partial class Property
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int PropertyId { get; set; }
[StringLength(8)]
public string ReferenceNumber { get; set; }
[StringLength(4)]
public string CaseOwner { get; set; }
public int AmountBorrowed { get; set; }
[ForeignKey("SecurityAddressId")]
public Address Security { get; set; }
[ForeignKey("CorrespondenceAddressId")]
public Address Correspondence { get; set; }
public List<Occupier> Occupier { get; set; }
public TenureTypes Tenure { get; set; }
public JurisdictionTypes Jurisdiction { get; set; }
public FunderTypes Funder { get; set; }
public Property()
{
Occupier = new List<Occupier>();
}
}
Occupier
[Table("Occupier")]
public partial class Occupier
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int OccupierId { get; set; }
public Honorifics Title { get; set; }
[StringLength(32)]
public string FirstName { get; set; }
[StringLength(32)]
public string LastName { get; set; }
public DateTime Dob { get; set; }
[StringLength(32)]
public string Relationship { get; set; }
[Required]
public int PropertyId { get; set; }
[ForeignKey(PropertyId)]
public Property Property {get; set;}
}
Related
I'm still studying Entity Framework and tried to create a model including the foreign keys.
But when I tried to migrate the code, I got this error
Introducing FOREIGN KEY constraint 'FK_dbo.QuestionResults_dbo.QuestionsTables_QuetionsTableId' on table 'QuestionResults' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints
These are my model classes:
public class MainDetails
{
[Key]
public int Id { get; set; }
public string Language { get; set; }
[Required]
public string CustomerName { get; set; }
[Required]
public string ContactNumber { get; set; }
public string EmailAddress { get; set; }
[DisplayName("Service Type")]
[ForeignKey("QuestionsTable")]
public int ServiceTypeId { get; set; }
public virtual QuestionsTable QuestionsTable { get; set; }
[Required]
public string VehicleNumber { get; set; }
[Required]
public string ServiceLocation { get; set; }
public string Suggestion { get; set; }
public bool Status { get; set; } = true;
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
[Display(Name = "Created Date")]
public DateTime CreatedDate { get; set; } = DateTime.Now;
public virtual QuestionResults QuestionResults { get; set; }
public virtual IList<QuestionResults> QuestionResultsMainlist { get; set; }
public virtual IList<QuestionsTable> QuestionsTables { get; set; }
}
public class QuestionsTable
{
[Key]
public int Id { get; set; }
public string ServiceType { get; set; }
public string Question { get; set; }
public virtual IList<MainDetails> MainDetailsServiceType { get; set; }
public QuestionsTable()
{
MainDetailsServiceType = new List<MainDetails>();
}
}
public class QuestionResults
{
[Key]
public int Id { get; set; }
[DisplayName("MainDetail ID")]
[ForeignKey("MainDetails")]
public int MainDetailsId { get; set; }
public virtual MainDetails MainDetails { get; set; }
[DisplayName("MainDetail ID")]
[ForeignKey("QuestionsTable")]
public int QuetionsTableId { get; set; }
public virtual QuestionsTable QuestionsTable { get; set; }
[Required]
public string CustoAnswer { get; set; }
}
This is the table structure I wanted to create:
To resolve this you can use the EF Model Builder
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<QuestionsTable>()
.HasRequired(a => a.MainDetails)
.WithOptionalDependent()
.WillCascadeOnDelete(false); //This is the important row
}
You'll have to play around with the type of relationship you would like along with whether you specify explicitly the foreign key. If you haven't seen this model builder before have a read here: https://learn.microsoft.com/en-us/ef/core/modeling/
Upon breaking your scenario down I noticed some "oddities". I reduced the noise in the domain model to from your example to this
public class MainDetails
{
[Key]
public int Id { get; set; }
[ForeignKey("QuestionsTable")]
public int ServiceTypeId { get; set; }
public virtual QuestionsTable QuestionsTable { get; set; }
public virtual QuestionResults QuestionResults { get; set; }
public virtual IList<QuestionResults> QuestionResultsMainlist { get; set; }
public virtual IList<QuestionsTable> QuestionsTables { get; set; }
}
public class QuestionsTable
{
[Key]
public int Id { get; set; }
public string ServiceType { get; set; }
public string Question { get; set; }
public virtual IList<MainDetails> MainDetailsServiceType { get; set; }
}
public class QuestionResults
{
[Key]
public int Id { get; set; }
[ForeignKey("MainDetails")]
public int MainDetailsId { get; set; }
public virtual MainDetails MainDetails { get; set; }
[ForeignKey("QuestionsTable")]
public int QuetionsTableId { get; set; }
public virtual QuestionsTable QuestionsTable { get; set; }
}
I few things I noted.
MainDetails contains both One-To-Many (QuestionTable) and Many-To-Many (IList) relationships? I'm unsure on your intention
QuestionsResults contains singular relationships to both entities which aren't replicated in the QuestionTable class? that's fine if it's intentional
ServiceType is a string in QuestionsTable but you are expecting an int as the foreign key in MainDetails?
I'm using EF Core 2.2
the Code with the error
var ClientCase= _context.Client_Cases.Include(a=>a.Case_Sessions). FirstOrDefault(x => x.Id == id);
The Error
System.Data.SqlClient.SqlException: 'Invalid column name
'Client_CaseId'. Invalid column name 'Case_LevelId'. Invalid column
name 'Client_CaseId'. Invalid column name 'Court_CircleId'. Invalid
column name 'Court_HallId'.'
Entities
1- Parent Client_Case
public class Client_Cases
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
public string Opponent { get; set; }
public DateTime? StartDate { get; set; }
public DateTime Recieve_Date { get; set; }
[ForeignKey("Clients")]
public long? ClientID { get;set;}
public Clients Client { get; set; }
[ForeignKey("Case_Levels")]
public long? LevelID { get; set; }
public virtual Case_Levels Case_Levels { get; set; }
[ForeignKey("Case_Types")]
public long? TypeID { get; set; }
public virtual Case_Types Case_Types { get; set; }
[ForeignKey("Court_Circles")]
public long? CircleID { get; set; }
public virtual Court_Circles Court_Circles { get; set; }
[ForeignKey("Court_Halls")]
public long? HallID { get; set; }
public virtual Court_Halls Court_Halls { get; set; }
[ForeignKey("Courts")]
public long? CourtID { get; set; }
public virtual Courts Court { get; set; }
[ForeignKey("Case_Status")]
public long? StatusID { get; set; }
public Case_Status Case_Status { get; set; }
[ForeignKey("Lawyers")]
public long? LawyerID { get; set; }
public virtual LawyersData Lawyers { get; set; }
public string Description { get; set; }
public string Code { get; set; }
public string CaseNo { get; set; }
public List<Case_Sessions> Case_Sessions { get; set; }
}
Detail Entity Case_Session
public class Case_Sessions
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Id { get; set; }
[ForeignKey("Client_Cases")]
public long? CaseID { get;set;}
public Client_Cases Client_Case { get; set; }
[ForeignKey("Case_Levels")]
public long? LevelID { get; set; }
public Case_Levels Case_Level { get; set; }
[ForeignKey("Court_Circles")]
public long? CircleID { get; set; }
public Court_Circles Court_Circle { get; set; }
[ForeignKey("Court_Halls")]
public long? HallID { get; set; }
public Court_Halls Court_Hall { get; set; }
[ForeignKey("Case_Status")]
public long? StatusID { get; set; }
public Case_Status Case_Status { get; set; }
public DateTime Session_Date { get; set; }
public string Judge_Name { get; set; }
public string Session_Result { get; set; }
public string Notes { get; set; }
}
If I get the parent without including the child it works.
If I get the details, it works.
I know the error that EF Core Create its own naming convention for the Foreign keys
but I think the tag Foreign Key override that naming convention
Now where I am wrong?
[ForeignKey("")] Mean? name the property you have added in class to become a foreign key. e.g:
public long? CaseID { get;set;}
[ForeignKey("CaseID")]
public Client_Cases Client_Case { get; set; }
public long? CircleID { get; set; }
[ForeignKey("CircleID")]
public Court_Circles Court_Circle { get; set; }
You can use annotations like above, In your case, below correction needed:
[ForeignKey("Client")] // it should be [ForeignKey("Client")] not an extra s if you using entities name in annotation.
public long? ClientID { get;set;}
public Clients Client { get; set; }
this should be your relationship for lawyer:
[ForeignKey("Lawyers")]
public long? LawyersID { get; set; }
public virtual LawyersData Lawyers { get; set; }
I am assuming that the type of primary key in LawyersData table is long?.
There are no primary or candidate keys in the referenced table 'dbo.Client_Master' that match the referencing column list in the foreign key 'FK_dbo.Client_Question_Master_dbo.Client_Master_client_id'.
Could not create constraint or index. See previous errors.
My Client_Master Model
public class Client_Master
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long Client_Id { get; set; }
public string Client_Name { get; set; }
public string Client_Address { get; set; }
public string Client_Email { get; set; }
public string Client_Phone { get; set; }
[DefaultValue(" ")]
public string Client_Country { get; set; }
[DefaultValue(" ")]
public string Client_State { get; set; }
[DefaultValue(" ")]
public string Client_Postcode { get; set; }
public bool Is_Active { get; set; }
public long? Created_By { get; set; }
public DateTime? Created_Date { get; set; }
[ForeignKey("Business_Master")]
public long? Business_Id { get; set; }
[ForeignKey("Categories")]
public long? Category_Id { get; set; }
public virtual Categories Categories { get; set; }
public virtual Business_Master Business_Master { get; set; }
[JsonIgnore]
public virtual ICollection<Client_Question_Master> Client_Question_Master { get; set; }
}
And My Client_Question_Master Modal
public class Client_Question_Master
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long client_question_master_id { get; set; }
[ForeignKey("Client_Master")]
public long? client_id { get; set; }
public virtual Client_Master Client_Master { get; set; }
[ForeignKey("Question_Types")]
public long? question_type_id { get; set; }
public virtual Question_Types Question_Types { get; set; }
public string question { get; set; }
public long order_no { get; set; }
public bool isContribute { get; set; } = true;
[ForeignKey("Section_Master")]
public long? section_id { get; set; }
public virtual Section_Master Section_Master { get; set; }
public double amount { get; set; }
public bool isActive { get; set; } = true;
public bool isRequired { get; set; } = true;
public bool isComment { get; set; } = true;
public string values { get; set; }
public bool isRevenue { get; set; }
public bool isStaff { get; set; }
public bool isMarketing { get; set; }
public DateTime created_date { get; set; } = DateTime.Now;
}
After add-migration during updating database it is giving me error.
Your usage of the ForeignKey attribute is the wrong way round, when using a nullable foreign key.
For example you use:
[ForeignKey("Client_Master")]
public long? client_id { get; set; }
public virtual Client_Master Client_Master { get; set; }
However it should be:
public long? client_id { get; set; }
[ForeignKey("client_id")]
public virtual Client_Master Client_Master { get; set; }
You tell EntityFramework what property is the foreign key. This prevent it from creating a field that has the same datatype as the primary key.
Check your edmx file.Edmx may not have that column as Primary key in another table which you are using as foreign key.
When I'm using the following code, the tables are generated successfully with the Primary key and Foreign Key relations.
[Table("tblDepartments")]
public class DepartmentModel
{
[Key]
public int DepartmentID { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public ICollection<EmployeeModel> Employees { get; set; }
}
[Table("tblEmployees")]
public class EmployeeModel
{
[Key]
public int EmployeeID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
public virtual DepartmentModel DID { get; set; }
}
But when I use the following Code, I'm Getting error:
[Table("tblDepartments")]
public class DepartmentModel
{
[Key]
public int DepartmentID { get; set; }
public string Name { get; set; }
public string Location { get; set; }
public ICollection<EmployeeModel> Employees { get; set; }
}
[Table("tblEmployees")]
public class EmployeeModel
{
[Key]
public int EmployeeID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
[ForeignKey("DeptID")]
public virtual DepartmentModel DID { get; set; }
}
ERROR:
The ForeignKeyAttribute on property 'DID' on type
'MvcApplication1.Models.EmployeeModel' is not valid. The foreign key
name 'DeptID' was not found on the dependent type
'MvcApplication1.Models.EmployeeModel'. The Name value should be a
comma separated list of foreign key property names.
Please Help. Thanks in advance.
The problem is with your EmployeeModel as you are missing departmentid field in your table as suggested by Gert. you can use the below for EmployeeModel
[Table("tblEmployees")]
public class EmployeeModel
{
[Key]
public int EmployeeID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
public int DeptID { get; set; } //<-- You forgot to add this
[ForeignKey("DeptID")]
public virtual DepartmentModel DID { get; set; }
}
Put the foreign key as a property inside your model then have the navigation property point to it.
public class EmployeeModel
{
[Key]
public int ID { get; set; }
public int DeptID { get; set; }
public string Name { get; set; }
public string Gender { get; set; }
public string City { get; set; }
[ForeignKey("DeptID")]
public virtual DepartmentModel DID { get; set; }
}
In '[ForeignKey("DeptID")]' you need to have the property DeptID in the model.
If you don't want it but just the name DeptID on the foreign key field you need to use fluent interface to configure the relationship i.e.
HasOptional(t => t.DID)
.WithMany()
.Map(d => d.MapKey("DeptID"));
All,
I need to add a domain class for a new key table that relates a table of club members ([dbo].NewClubProspect) to emails ([dbo].NewClubEmail) sent to them.
I am not sure how to set this up in the domain classes.
Question
Need to annotate the key table (NewClubProspectNewClubEmail) Since both properties are foreign keys, not sure if I need an actual primary key, too? How do I annotate this?
Here is a diagram of how the tables relate. The table on the bottom of the diagram (NewClubProspectNewClubEmail) is the new table that I need to create in the database and in code, in a domain class.
Here are my domain classes (chopped down for brevity)
public class NewClub
{
public NewClub()
{
NewClubProspects = new List<NewClubProspect>();
NewClubEmails = new List<NewClubEmail>();
}
public int Id { get; set; }
public string NewClubName { get; set; }
public string NewClubLocation { get; set; }
public string NewClubType { get; set; }
public string NewClubCity { get; set; }
public string NewClubState { get; set; }
public string NewClubCountry { get; set; }
public virtual List<NewClubProspect> NewClubProspects { get; set; }
public virtual List<NewClubEmail> NewClubEmails { get; set; }
}
public class NewClubProspect
{
[Key]
public int Id { get; set; }
//Foreign Key
public int NewClubId { get; set; }
public bool IsConverted { get; set; }
public string ProspectFirstName { get; set; }
public string ProspectLastName { get; set; }
public string ProspectEmail { get; set; }
public virtual NewClub NewClub { get; set; }
public virtual List<NewClubEmail> NewClubEmails { get; set; }
}
public class NewClubEmail
{
//Primary key
[Key]
public int Id { get; set; }
//Foreign Key
public int NewClubId { get; set; }
public string Subject { get; set; }
public virtual List<NewClubProspect> Recipients { get; set; }
public string Body { get; set; }
public DateTime CreateDate { get; set; }
public DateTime ModifiedDate { get; set; }
public DateTime? SentDate { get; set; }
public NewClub NewClub { get; set; }
public NewClubEmail()
{
Recipients = new Collection<NewClubProspect>();
}
}
//---------------------------------------------------------
// Not sure what to do here. They are both foreign keys
//---------------------------------------------------------
public class NewClubProspectNewClubEmail
{
public int NewClubEmail_Id {get; set;}
public int NewClubProspect_Id {get; set;
}
Just mark both as Key:
[Key]
public int NewClubEmail_Id {get; set;}
[Key]
public int NewClubProspect_Id {get; set;}