c# - How to get an object with non-primitive parameters from Database.SqlQuery? -
could please advise should in question described below?
i have class "car" mapped database table (using ef code first) , it has primitive object parameters.
also have second class "user" mapped database table , class has object parameter car.
could please tell me, how can first object db, used following code ef?
dbcontext.database.sqlquery<user>("dbo.getfirstuser") my function dbo.getfirstuser:
select userid, firstname, secondname, carid dbo.user when try it, query returns object primitive parameters, object car null.
i thankful advice.
thanks.
using system.componentmodel.dataannotations; using system.componentmodel.dataannotations.schema; namespace testtimerconsole { [table("car", schema = "usr")] class car { [key] public int carid { get; private set; } public string name { get; private set; } } } using system.componentmodel.dataannotations; using system.componentmodel.dataannotations.schema; namespace testtimerconsole { [table("user", schema = "usr")] class user { [key] public int userid { get; private set; } public string firstname { get; private set; } public string secondname { get; private set; } [foreignkey("car")] public int carid { get; private set; } public car car { get; private set; } } }
you selecting carid. need select car object database. there several ways can this.
examples
using (var context = new dbcontext()) { var query = u in context.users join c in context.car on u.carid equals c.carid select new user { userid = u.userid, firstname = u.firstname, lastname = u.lastname, car = new car() { carid = c.carid, name = c.name } } } after selecting user using stored procedure select car
user user = dbcontext.database.sqlquery<user>("dbo.getfirstuser"); car car = dbcontext.user.firstordefault(x => x.carid == user.carid); //or create stored proc if want. i think updated stored procedure return everything. have make sure properties map correctly though.
so change the stored procedure this:
select userid, firstname, secondname, carid, c.name [car.name] dbo.user u inner join dbo.car c on u.carid = c.carid
Comments
Post a Comment