Entity Framework - Invalid Column Error on non-existent column - sql-server

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.

Related

Search data in multiple tables

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; }
}
}

Which tables should have a timestamp column? Concurrency check with Entity Framework, XAF, DDD

I am using Dev Express XAF WinForms to write an ERP system.
In practice I have found that my DBContext needs to have a DBSet for most of my business objects.
I am trying to figure out which tables should have a timestamp column for optimistic concurrency purposes.
For example I have
[NavigationItem("Sales")]
public class SalesOrder : BaseSalesHeader
{
public SalesOrder()
{
Lines = new List<SalesOrderLine>();
}
[Aggregated]
public virtual List<SalesOrderLine> Lines { get; set; }
}
[NavigationItem("Production")]
public class SalesOrderLine : BaseSalesProductTransactionLine
{
[Browsable(false)]
[System.ComponentModel.DataAnnotations.Required]
[RuleRequiredField(DefaultContexts.Save)]
[ForeignKey("SalesOrder_Id")]
public virtual SalesOrder SalesOrder { get; set; }
}
In my DBContext I have
public DbSet<SalesOrder> SalesOrders { get; set; }
public DbSet<SalesOrderLine> SalesOrderLines { get; set; }
In my OnModelCreating I have
modelBuilder.Entity<SalesOrder>().HasMany(p => p.Lines).WithRequired(t => t.SalesOrder).WillCascadeOnDelete(true);
Sales Order Lines are accessible from 2 Menus
As part of a Sales Order, and as a Sales Order Line Item under the Production navigation item.
I think I should have the timestamp field in the SalesOrders table. Should I also have it in the SalesOrderLine table ?
Here is the linked question at Dev Express Support
Whether or not you want to apply optimistic concurrency (OC) for an entity is something we can't decide for you. But there are some things to consider:
It's not necessarily true that only entities that are exposed as DbSet will need OC. After all, any mapped entity can be changed when it's reachable through navigation properties. SalesOrder exposes SalesOrderLines by its Line property, so by all means you can create some UI that only modifies SalesOrderLines while it only receives a SalesOrder (including its lines) as input.
In Entity Framework (and other ORMs), a parent isn't marked as modified when one of its children is modified. If you save a SalesOrder with modified SalesOrderLines, there will only be update statements for the lines.
So, yes, you probably want to protect SalesOrderLine by OC as well. But also consider this:
OC isn't for free. When you add a RowVersion* column to a table (and map it as rowversion appropriately), Entity Framework will read its value after each insert or update. I've experienced that this may considerably harm performance in processes that update relatively many records (EF doesn't shine there anyway). Also, when a concurrency conflict occurs, EF will read the current values of the conflicting record(s) from the database.
I've seen applications where the performance impact from OC is mitigated by marking a parent object (having OC) as modified when any of its children is modified. I think that's rather contrived, but it may be something to consider.
* TimeStamp is a deprecated data type
Any table that could be updated by more than 1 user at the same time should really have some sort of timestamp associated with it. Personally, I put a timestamp on every table just to be doubly sure.
You can mark this timestamp field with a [Timestamp] attribute and EF will know what to do with it automatically.

How can I have multiple instances of a column that itself holds a foreign key reference?

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?

Required-to-required relationship with cascading delete (Entity Framework)

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).

Cycles and/or Multiple Cascade Paths with Auto-Generated Linking Table

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).

Resources