I have a class that has a many-to-many relation (with some additional relation information) to instances of the same class, like this:
public class Aaa
{
[Key]
[MaxLength(25)]
public string Handle { get; set; } = null!;
}
public class Bbb
{
[Key]
[MaxLength(25)]
public string Handle { get; set; } = null!;
[Required]
[Index]
[MaxLength(25)]
public string FromAaaHandle { get; set; } = null!;
[Required]
[Index]
[MaxLength(25)]
public string ToAaaHandle { get; set; } = null!;
public int SomeOtherRelationStuff { get; set; }
[ForeignKey("FromAaaHandle")]
public virtual Aaa FromAaa { get; set; } = null!;
[ForeignKey("ToAaaHandle")]
public virtual Aaa ToAaa { get; set; } = null!;
}
That results in an Microsoft.Data.SqlClient.SqlException telling me that the foreign key constraints "may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints"
Whats the problem here? Removing an entry from table Bbb should not have any impact on table Aaa. Removing an entry from Aaa might cause entries to be removed from Bbb but should have no impact on other entries in Aaa. I don't see any cycles
"may cause cycles or multiple cascade paths." Here Aaa would cascade to all the Bbb's referencing it as FromAaa or ToAaa. This is multiple cascade paths, and isn't allowed.
Related
I have a model class:
public class UserProfile
{
public string UserID { get; set; }
public string Name{ get; set; }
public ICollection<AddressMaster> AddressMaster { get; set; }
}
The above class have a 1 to many relationship with AddressMaster model class given below:
public class AddressMaster
{
public string AddrID{ get; set; }
public string AddressLine1{ get; set; }
public UserProfile UserProfile { get; set; }
public TheatreLocation TheatreLocation { get; set; }
}
The problem is, there is one other model also that has a 1 to many relationship with addressmaster, which is:
public class TheatreLocation
{
public string LocationID { get; set; }
public string Name{ get; set; }
public ICollection<AddressMaster> AddressMaster { get; set; }
}
So instead of having foreign key at the addressmaster, how can we have a intermediate table between addressmaster and the userprofile & another such table b/w addressmaster and theatre?
Or am i getting the whole concept wrong?
Thanks.
So instead of having foreign key at the addressmaster, how can we have
a intermediate table between addressmaster and the userprofile &
another such table b/w addressmaster and theatre?
If you do not want to set any foreign key and add a intermediate table.Design like below:
public class UserProfile
{
[Key]
public string UserID { get; set; }
public string Name { get; set; }
}
public class AddressMaster
{
[Key]
public string AddrID { get; set; }
public string AddressLine1 { get; set; }
}
public class UserAddress
{
[Key]
public string AddrID { get; set; }
public string UserID { get; set; }
}
Add the primary key to the intermediate table UserAddress.The AddrId could only has one value,but the UserID could have many value which is like one-to-many relationship.
Or am i getting the whole concept wrong?
Nothing wrong.Using navigation property like what you did is also good.
Your table definitions would probably wind up something like this:
UserProfile
UserId PK
Theather
TheatreId PK
Address
AddrID PK
AddressLine1
UserAddress
UserId PK & FK
AddressId FK
TheatreAddress
TheatreID PK & FK
AddressId FK
This is just good normalisation - i.e. you have a generic 'address' table in the database. Several entities may have an address and have either one-many or many-many relationships with addresses, but a specific address only needs to be recorded once.
The PK on the intermediate table only on the UserId (for example) ensures that this is one-many and not many-many.
I have two simple classes with a Primary Key and FK relationship.
In the Sub_Department class, I get the error
SqlException: Invalid column name 'DepartmentID1'.
System.Data.SqlClient.SqlCommand+<>c.b__108_0(Task result)
Here is my code
public class Departments_Category_Registration
{
[Key]
public int CategoryID { get; set; } // This is the PK
public Departments DepartmentID { get; set; } // this is a FK
and my Departments class with the PK
public class Departments
{
[Key]
public int DepartmentID { get; set; }
[Display(Name ="Departments")]
[Required]
public string Department_Name { get; set; }
[Display(Name ="Departments")]
[Required]
public string Description_Long { get; set; }
[Display(Name ="Short Description_Short")]
[Required]
public string Description_Short { get; set; }
public bool IsEnabled { get; set; }
}
however if I update my db to change the FK to department1 it works, funny thing is that I never used 1 in my code, I had changed it from ID to DepartmentID (if that helps)
Secondly, I thought I ask, if its wise to create a separate controller for each model or not ?
Ehi
I am getting error while trying to run my MVC application
Introducing FOREIGN KEY constraint 'FK_dbo.Passages_dbo.Localizations_ToID' on table 'Passages' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
Could not create constraint or index. See previous errors'
I`ve seen many posts but I couldn't get what should I do now.
There are my models:
public class Passage
{
[Key]
public int ID { get; set; }
public int FromID { get; set; }
[ForeignKey("FromID")]
public Localization FromLocalizaton { get; set; }
public int ToID { get; set; }
[ForeignKey("ToID")]
public Localization ToLocalization { get; set; }
public DateTime DepartureTime { get; set; }
public DateTime ArrivalTime { get; set; }
public DateTime? AdditionalTime { get; set; }
public bool Weekend { get; set; }
public int Seats { get; set; }
}
public class Localization
{
[Key]
public int ID { get; set; }
public string Province { get; set; }
public string City { get; set; }
public string PostalCode { get; set; }
public string StreetAdres { get; set; }
}
Passage has two foreign key refers to Lozalization with one to one relationship
The issue came from this:
Passage has two foreign key refers to Lozalization with one to one relationship
Because by default those two relationships are required in Passage (look at foreign key FromID and ToID there are not Nullable<int> or int?) hence Code First create cascade delete action on those relations. However two cascade deletions will be applied on the same table which is not allowed.
To correct this issue, you have two solutions:
Make one of the foreign key property Nullable<int> which by default not create a cascade delete action on that relationship.
Or you can disable cascade delete action by using Fluent API like this :
// Assuming that you want to disable cascade deletion with ToLocalization
modelBuilder.Entity<Passage>()
.HasRequired(p => p.ToLocalization)
.WithMany()
.WillCascadeOnDelete(false);
I have one to one relationship with foreign keys but the Cascade Delete is not enabled for some reason. The sample code is below.
public class AppRegistration
{
public int AppRegistrationId { get; set; }
[Required]
[StringLength(50)]
[Display(Name = "Username")]
public string UserName { get; set; }
[Required]
[StringLength(100)]
public string Password { get; set; }
[StringLength(20)]
public string StudentOrAgent { get; set; }
// navigation properties
public virtual AppStatus AppStatus { get; set; }
public virtual Agreement Agreement { get; set; }
public virtual AnotherTable AnotherTable { get; set; }
}
The dependent table with a foreign key is below.
public class Agreement
{
[Key]
[ForeignKey("AppRegistration")]
public int AppRegistrationId { get; set; }
public DateTime DateAgreed { get; set; }
public virtual AppRegistration AppRegistration { get; set; }
}
When I try to delete an entry from the generated AppRegistrations table I get a Reference constraint conflict.
I tried putting [Required] on the navigation property in the dependent table but it doesn't do anything - the Update-Database command shows the No pending code-based migrations. message. Any ideas? Thanks.
Update:
I'm getting the following error message:
The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.AppStatus_dbo.AppRegistrations_AppRegistrationId". The conflict occurred in database "MVCapp", table "dbo.AppStatus", column 'AppRegistrationId'.
I decided to work out the cascade delete problem in a separate sample project. I found the following blog & MSDN pages very useful.
http://blog.bennymichielsen.be/2011/06/02/entity-framework-4-1-one-to-one-mapping/
http://msdn.microsoft.com/en-us/library/gg671256%28v=VS.103%29.aspx
http://msdn.microsoft.com/en-us/library/gg671273%28v=VS.103%29.aspx
Using the Code First approach create the following Model.
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public virtual Book Book { get; set; }
}
public class Book
{
public int CategoryId { get; set; }
public string BookTitle { get; set; }
public string BookAuthor { get; set; }
public string BookISBN { get; set; }
public virtual Category Category { get; set; }
}
(I realize the entity names suggest one-to-many relationship, but I am trying to model 1-to-1 relationship, as in my original question at the top.)
So, in the above model each Category can only have one Book.
In your DbContext-derived class add the following.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Book>()
.HasKey(t => t.CategoryId);
modelBuilder.Entity<Category>()
.HasRequired(t => t.Book)
.WithRequiredPrincipal(t => t.Category)
.WillCascadeOnDelete(true);
}
(The following namespaces are required for the above code: System.Data.Entity, System.Data.Entity.ModelConfiguration.Conventions.)
This properly creates the 1-to-1 relationship. You'll have a primary key in each table and also a foreign key in Book table with ON DELETE CASCADE enabled.
In the above code, on the Category entity I used WithRequiredPrincipal() with t => t.Category argument, where the argument is the foreign key column in the dependent table.
If you use WithRequiredPrincipal() without an argument you'll get an extra column in the Book table and you'll have two foreign keys in the Book table pointing to CategoryId in Category table.
I hope this info helps.
UPDATE
Later on I found answer directly here:
http://msdn.microsoft.com/en-us/data/jj591620#RequiredToRequired
A reason why you're not getting cascading delete is because your relationship is optional.
If you want the relationship required i.e. an AppRegistration has to have one Agreement you can use (cascading delete configured automatically):
public class Agreement
{
...
[Required]
public AppRegistration AppRegistration{ get; set; }
}
If you want the relationship to be optional with cascading delete you can configure this using Fluent API:
modelBuilder.Entity<AppRegistration>()
.HasOptional(a => a.Agreement)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
Person and EHR(electronic health record) are one to one related.
Person has EHRId nullable and EHR has PersonId not nullable.
At the same time EHR and Person must be many to many related.
Because a person can have many medics (represented by person entity) and a medic can have many EHRs.
I would like to have extra attributes on the join table.
I dont know how to define this in EF.
Please help.
Here are my classes.
public class Person
{
public int ID { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public ICollection<UserSpecialist> patients { get; set; }
public int ehrID { get; set; }
public virtual EHR ehr { get; set; }
}
public class EHR
{
public int ID { get; set; }
public bool asthmatic{ get; set; }
public ICollection<UserSpecialist> specialists { get; set; }
public int PersonID { get; set; }
public virtual Person Person { get; set; }
}
public class UserSpecialist
{
public int ID { get; set; }
public DateTime creationDate { get; set; }
public int PersonID { get; set; }
public int EHRID { get; set; }
public virtual Person Person { get; set; }
public virtual EHR EHR { get; set; }
}
When EF tries to create the database throws this error
Unable to determine the principal end
of an association between the types
'Project.Person' and 'Project.EHR'.
The principal end of this association
must be explicitly configured using
either the relationship fluent API or
data annotations.
Please help
Person and EHR are not one-to-one related and they cannot be in EF. What you have defined is bidirectional one-to-many. You have also declared both relations as required because FK's are not nullable.
Real one-to-one can be defined in EF only if EHR's PK (Id) is also FK to Person. Once you define this the part with many-to-many becomes really strange because Person will be related with EHRs of other persons. You domain description is most probably not correct.