I have been using EF5 via Code First successfully so far to build out my database from my models. However, I recently ran into a (fairly) common issue of cycles/multiple cascade paths. I understand what the problem is and normally, I fix it by writing rules against my entities to disable CascadeOnDelete down one side of the branch. The difference with this scenario and my current one, is that I typically am creating the middle "join" table in a many-to-many relationship.
So, for example, I may have: Users => UserLeagues <= Leagues
And then I do this:
modelBuilder.Entity<UserLeagues>()
.HasRequired(u => u.League)
.WithMany()
.HasForeignKey(l => l.LeagueId)
.WillCascadeOnDelete(false);
Where I have created the UserLeague table (it requires some additional information so this makes sense). In my most recent case, I just needed to create a many-to-many relationship. So, I didn't bother to create this middle table. Instead, I let EF auto-generate it.
As a result, I am unsure of how to stop the cascade delete down the one side because I don't have access to the UserLeagues table directly like I do if I manually created that many-to-many table. Any advice? Here are my models...
public User {
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<League> Leagues { get; set; }
}
public League {
public int Id { get; set; }
public int Score { get; set; }
public virtual ICollection<User> Users { get; set; }
}
When you let EF auto-generate (many-to-many relationship and the support table) - you have no way of manually deleting the actual records in the join table, once the relationship is removed (since you don't have that table mapped to an entity).
Hence the cascade deletes need to be 'on' by default. That's 'by convention'.
You could remove that convention all together (for all many to many - and their fk-s involved)...
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
Another way to do that on a case by case basis - would be to change the migration scripts
(providing you're using migrations).
When migrations generate the pseudo code - it has something like
.ForeignKey("dbo.Leagues", t => t.League_Id, cascadeDelete: true)
Just remove the , cascadeDelete: true parameter.
But then you'll end up with phantom records (i.e. you'll need to resort to manual SQL or occasional cleanup to remove the junk records).
Related
Let’s say, I have 2 tables in Azure SQL – Employee & Address and both the tables have common field, say Address Id.
Question:
If I create separate indexes for tables, can I search the data in both indexes from single search API? Is it possible to join 2 indexes? Just cross checking if such functionality exists.
Another option I am aware of is – load data from both the tables to single index using solution given in below. Is this possible only via .NET API? Can we develop it from Portal?
https://learn.microsoft.com/en-us/azure/search/tutorial-multiple-data-sources
Any other recommended approach?
If I create separate indexes for tables, can I search the data in both
indexes from single search API? Is it possible to join 2 indexes? Just
cross checking if such functionality exists.
No. Search is only limited to a single index. You would need to combine the search results from multiple indexes on the client side.
Another option I am aware of is – load data from both the tables to
single index using solution given in below. Is this possible only via
.NET API? Can we develop it from Portal?
You should be able to do it from the portal. Essentially the idea is to create two data sources (one for each table), two indexers (one for each data source) and have these indexers populate the data into a single index.
Another idea would be to create a database view that combines the data from these two tables and use that view as the data source for your index. That way you don't have to create separate data sources and indexers.
just use this:
namespace WebApplication1.Data
{
public class allstudents
{
[Key]
public int Id { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Country { get; set; }
}
}
For my API I'm using Entity Framework Core with code first migrations. I've created some relations which are working fine. Now, I've added another relation (one to many) and suddenly I'm slapped around the ears with this error:
Cannot insert explicit value for identity column in table 'Companies' when IDENTITY_INSERT is set to OFF."
Offcourse, I must be doing something wrong but I just can't figure out what. I've come across more questions like this where the answer was "set IDENTITY_INSERT to ON" but that doesn't work for me since EF is handling everything.
My Company class which can belong to a Group:
public class Company
{
// Primary key
public int Id { get; set; }
// The optional Id of a Group
public int? GroupID { get; set; }
...
}
And the Group class:
public class Group
{
// Primary key
public int Id { get; set; }
// Name of the Group
public string Name { get; set; }
// List of Companies in this group
public IEnumerable<Company> Companies { get; set; }
}
The code used for handling the POST:
// POST api/groups
[HttpPost]
public async Task<IActionResult> Post([FromBody] Group group)
{
try
{
if (ModelState.IsValid)
{
_context.Groups.Add(group);
await _context.SaveChangesAsync();
return CreatedAtRoute("GetGroup", new { id = group.Id }, group);
}
return BadRequest(ModelState);
}
catch (Exception e)
{
return BadRequest($"Unable to create: {e.Message}");
}
}
In my database, all columns, index and keys are created as expected and just like every other one to many relationship I've got in my API. But this specific case just seems to end up in misery...
The class I'm trying to add to the database:
Problem is that there's no hint for EF to know if Company (under Group relationship) is being explicitly inserted or if it is supposed to use the pre-existing one from database.
Since those instanced are disconnected from DbContext there is no indication whether they exist or not on the database by the time EF tries to generate its SQL command.
There is no easy way here, at least there was none by the time I've played with EF Core.
You should either:
Change your code to only use the ID instead of the navigation property so you'll avoid this whenever possible, or;
Change your code to fetch related data (eg: fetch Company and attach it to Group) before saving desired data (eg: before saving Group).
So, for instance:
var companyDB = await context.Companies.SingleOrDefaultAsync(c => c.Id == group.Company.Id);
group.Company = companyDB;
context.Groups.Add(group);
await context.SaveChangesAsync();
Yes, you're making two trips to database. That's why I'd suggest using the first approach, so you can avoid this fetch and just save Group entity directly into DB.
That does not, however, prohibits you from sending a navigation instace of Company to your view. Just create some entity-related classes which will correlate to your database so you can load/save data using this entity type, and create a Dto object which will be your endpoint input/output whenever needed.
Binding one into another can be done by using AutoMapper, manual linq or other approaches.
This is because you are passing some value in a column which is set as identity (auto-increment).
I think the Group entity which you are inserting has the companies with the value of Id which it tries to insert in company table as child record. and it throws an error.
I had a similar problem when trying to save an entity (for ex., Cat) which had many-to-one relationships to existing entities (property Owner, pointing at Person). In addition to a) getting the relationship (Person) from the database before saving the entity (Cat), and b) adding another property (int PersonId) to the entity (Cat), I discovered what I think is the best solution: c) stick to "navigation" properties only (do not create extra int <<Name>>Id properties), and when referencing is needed, use cat.Owner = dbContext.Person.Attach(new Person { Id = 123 }).Entity;
Entity Framework lost tracking for some reason and Entity Framework needs to reestablish tracking for the entities that are already existing.
You can get the state of the entity's tracking with:
var entityTrackingState = _context.Entry(entity).State;
You can force Entity Framework to do tracking on the existing entities with:
_context.Entry(untrackedEntity).State = EntityState.Unchanged;
Where
_context
is an Entity Framework DbContext.
Forcing tracking resolved my issue, but it really should be debugged where Entity Framework is losing tracking.
I have 2 tables in a plain old 1-n relationship: Invoice and WorkOrder. An Invoice can have many WorkOrders and a WorkOrder can have a single Invoice. Earth-shaking, I know.
Here's my Invoice:
public class Invoice
{
public Guid Id { get; set; }
// some fields....
public virtual IList<WorkOrder> WorkOrders { get; set; }
}
Here's my WorkOrder:
public class WorkOrder
{
public Guid Id { get; set; }
public Guid InvoiceId { get; set; }
public virtual Invoice Invoice { get; set; }
}
When I go to query for Invoices, I get this error:
Invalid column name 'Invoice_Id2'.
When I look at the WorkOrder table in SSMS I find not one, but 3 columns referencing Invoice: InvoiceId, Invoice_Id, and Invoice_Id1.
Obviously something has gone very wrong in EF figuring out what I want it to do.
I did manage to find an FK for Invoice_Id2, which I deleted, but I'm still having the problem.
In my experience this type of error happens when EF is trying to match a relationship based on faulty navigational properties. For instance if you had:
public int InvoiceId { get; set; }
public virtual Invoice Invice { get; set; }
Notice the misspelling above. EF will expect there to be a column in the database called Invice_Id. I'd check your related entities for misnamed navigational properties.
So it turned out that I had made some mistakes not elaborated above (bc I didn't think they were relevant, natch). Namely I had a bunch of getter methods in my Invoice entity that returned IList<WorkOrder> and EF was mistakenly picking up on those as navigation properties.
As far as I can tell, once you've created a table that's been jacked up that way, you're better off dropping the offending tables, adding [NotMapped] attributes to the troublesome properties, and recreating the table. Hopefully you don't have important production data in those tables already. I lucked out there.
I was really surprised those getters would be picked up by the ORM as Navigation properties, so beware that in the future. Perhaps being less clever and doing straight methods in the future would be smarter.
I am new to Visual Studio so to start learning it I first of all downloaded a sample available at https://code.msdn.microsoft.com/ADPNET-Entity-Framework-2d1160cb and started working around it. Since I have fairly good knowledge of VB6 and SQL it did not take much time for me to understand the whole pattern the sample is based on. Had Microsoft given a detail explanation or a walk through of the sample it would have been much easier to understand the basics. However, I somehow managed to work around it and have build a small desktop application in wpf using Entity Framework and MVVM. But a point has come where I have got completely stuck up finding no way out. The problem is as under:
I have two tables. 1 Advocate and 2 Party. Table Advocate would contain names of advocates and would have a primary key. Similarly Party would have names and their respective primary keys.
Then I have another two tables 1. Case and 2 CaseDetail. Table Case would simply hold three columns: 1. CaseId 2. CaseNo and 3. Year. Table CaseDetail would have CaseDetailId as a primary key the CaseId as a Foreign Key. Now what I need is that a particular case could have multiple advocates and multiple petitioners. So the table CaseDetail would have two columns to hold advocateId and PartyId as a Foreign Keys.
If you look at the sample referred above you would not find how to deal with such a case. When I follow the pattern of the sample I get host of design time and runtime errors.
Anyways, after number of trials I have somehow manged to set the EF right but I doubt if it would serve any purpose since I need to have multiple instances of Petitioners and Advocates.
Here is the link to my edmx:
https://www.dropbox.com/s/rkarzod1lezdnqs/EDMX.png?dl=0
From the image it can be seen that I have four different foreign keys fldPetitioner, fldRespondent, fldAdvocate and fldSrAdvocate for which I too have navigation property to back track them which have multiplicity 0 or 1. Therefore, in such a scenario would I be able to have multiple instances on these columns?
Therefore, please suggest what strategy should be adopted in a scenario described above while developing WPF application using Entity Framework and MVVM.
I think it sounds like you're trying to use one-to-one relationships where there should be one-to-manys. Take a closer look at the relationship between Department and Employee from your linked MS sample. It results in '1 Department to many Employees'. This puts the DepartmentId against an entry in the Employee table, not the other way round, which is what I think you have at the moment. The analogous element from your question would be '1 CaseDetail to many Advocates'.
public class CaseDetail
{
//CaseDetail ID number
public int CaseDetailId { get; set; }
//...
//Any other properties go here
//...
//Navigation properties
public ICollection<Advocate> Advocates { get; set; }
/* Other collections would be executed similarly:
*
* public ICollection<Party> Petitioners { get; set; }
* public ICollection<Party> Respondents { get; set; }
*/
}
public class Advocate
{
//Advocate ID number
public int AdvocateId { get; set; }
//...
//Any other properties go here
//...
//Navigation properties
public int CaseDetailId { get; set; }
public CaseDetail CaseDetail { get; set; }
}
public class AdvocateConfiguration : EntityTypeConfiguration<Advocate>
{
public AdvocateConfiguration()
{
HasRequired(a => a.CaseDetail)
.WithMany(cd => cd.Advocates);
}
}
In the MS sample, you must have noticed that while entering data we assign Department to an employee although department to employee relationship is 1 to many. In my case the issue is that I want assign advocates to casedetail although the relationship casedetail to advocate is 1 to many. Here simply imagine a simple billing application where table invoice can be a master table having details in table invoicedetails where we can have multiple products as a foreign key. Considering the scenario please tell me whether or not there can be a derived entity with a navigation property to back track the products?
In my db model I got a table of Jobs and a table of JobResults.
The model definitions look the following:
public class Job
{
public int Id { get; set; }
public virtual JobResult Result { get; set; }
}
public class JobResult
{
public int JobId { get; set; }
public virtual Job Job { get; set; }
}
And the fluent API configuring the relationships is the following:
modelBuilder.Entity<Job>()
.HasRequired(x => x.Result)
.WithRequiredPrincipal(x => x.Job)
.WillCascadeOnDelete(true);
modelBuilder.Entity<JobResult>()
.HasKey(x => x.JobId);
As you see, it's a required-to-required relationship where they both share the Id of Job as primary key.
When a Job is deleted I obviously want the JobResult to be deleted as well (which is why I added the WillCascadeOnDelete()).
However when I update my database with the definitions above I get the following error:
Introducing FOREIGN KEY constraint 'FK_dbo.JobResults_dbo.Jobs_JobId'
on table 'JobResults' 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. See previous
errors.
This exclusively happens when I include the WillCascadeOnDelete().
Why is this happening?
This problem is caused by a possible cyclic cascading delete. This can happen in many forms, but it comes down to a record being deleted by two or more cascading delete rules in one time, so I ussume that you have another relationship where the Job entity is involved, and when you delete a record from the Job table, it is possible this delete will end trying to delete for both side the same record in another Table.
I suggest you take a look to this post and check if you don't have a situation like the example that is showed in the #KristofClaes' answer.
You can avoid such ambiguous delete paths by either disabling cascading delete using Fluent API or by defining some of the relationships as optional (with a nullable foreign key).