I am trying to get a output from Linq in particular format. This question has been rephrased -
SQL View- SomeView
Id T_Id 4 2 6 5 6 7
SQL table - User
T_Id fname lname 2 mary smith 5 john pope 7 steve blair
SomeView is QueryType, I used DbQuery to map it.
public class SomeView { public int Id {get; private set;} public int T_Id { get; private set; } public User User { get; set; } //can't navigate here } public class User { public int T_Id { get; set; } public string fname {get; set;} public string lname{get; set;} public SomeView SomeView{ get; set; } //can't navigate here }
There are no foreign key constraint defined in database as SomeView is SQL view. You can't use Navigation with QueryType. So mapping between User and SomeView is not possible or I don't know how to do.
public class SomeViewModel { public int Id { get; set; } public List Users{get; set;} } finally my linq in progress - from t in SomeView group new {t} by t.Id into grp select new SomeViewModel{ Id = grp.Key, Users = grp.Select(x => x.t.User).ToList() //need help here to get Users based on T_Id }
Final API data output should be in following format.
[{ "Id" : "4", "users":[{ "T_Id": 2, "fname": "mary", "lname": "smith" }] }, { "Id" : "6", "users":[{ "T_Id": 5, "fname": "john", "lname": "pope" }, { "T_Id": 7, "fname": "steve", "lname": "blair" } ] }]
SomeTable
toUser
. HenceList<User> Users
in the view model makes no sense - each record inSomeTable
can have 0 or 1User
. You'd better show the entity model - with proper navigation properties the LINQ query should be trivial - something likedb.SomeTable.Select(t => new SomeViewModel { Id = t.Id, User = t.User })
. – Ivan StoevSomeViewObj
is the many side of the relationship, so you need a single reference navigation propertypublic User User { get; set; }
mapped withHasOne
andT_Id
mapped withHasForeignKey
. This is how we access data in EF Core queries. If you want regular LINQ, take a look at C# join clause – Ivan Stoev