c# - View and Entity Framework data not right? -


i have view table when select view in sql server management studio works fine, when use entity framework data view it's different.

returndbfortesentities1 db = new returndbfortesentities1(); list<vjobs2> list = new list<vjobs2>(); list = db.vjobs2.tolist(); 

same number of records last 2 rows different.

i have table job applicant applicant can apply 2 jobs or more

applicantid    applicantname  jobid  jobname    1              mohamed       1    developer    1              mohamed       2    supporter  

but in list

applicantid    applicantname  jobid  jobname    1              mohamed       1    developer    1              mohamed       1    developer 

there subtle problem views when used entity framework.

if have table, use ef, need have primary key uniquely identify each row. typically, that's single column, e.g. id or that.

with view, don't have concept of "primary key" - view contains columns tables.

so when ef maps view, cannot find primary key - , therefore, use all non-nullable columns view "substitute" primary key.

i don't know these in case - should able tell .edmx model.

let's assume (applicantid, applicantname) 2 non-nullable columns ef uses "substitute" primary key. when ef goes read data, read first line (1, mohamed, 1, developer) , create object that.

when ef reads second line (1, mohamed, 2, it-supporter), notices "primary key" (1, mohamed) same before - doesn't bother creating new object values read, primary key same, hence must same object has read before, uses object instead.

so problem can't have explicit primary keys on view.

either can tweak ef model make clear ef e.g. (applicantid, jobid) primary key (you need make sure columns both non-nullable) - or need add "artificial" primary key view:

create view dbo.vjobs2    select         applicantid, applicantname, jobid, jobname,        rownum = row_number() over(order jobid)           dbo.yourbasetable 

by adding rownum column view, numbers rows 1, 2, ...., n, new, non-nullable column ef include "substitute pk" , since numbers sequential, no 2 rows have same "pk" values , therefore none erroneously replaced that's been read database already.


Comments

Popular posts from this blog

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -