c# - ADO.NET MVC Query foreign key -
i have 2 models connected foreign key, user , farm.
i want able select user query , type:
@model.farm.farmid
in view. wont work because farm prop null.
these 2 models:
model 1:
public class user { [key] public int userid { get; set; } public string username { get; set; } public string password { get; set; } public string passwordsalt { get; set; } public int money { get; set; } public int farmid { get; set; } [foreignkey("farmid")] public virtual farm farm { get; set; } }
model 2:
public class farm { public farm() { user = new hashset<user>(); } [key] public int farmid { get; set; } public datetime created { get; set; } public int age { get; set; } public virtual icollection<user> user { get; set; } }
get user query:
public user getuser(string username) { string sql = "select * users username = @username"; user user = null; using (sqlconnection connection = new sqlconnection(configurationmanager.connectionstrings["connectionstring"].connectionstring)) { seek { sqlcommand cmd = new sqlcommand(sql, connection); cmd.parameters.addwithvalue("@username", username); connection.open(); sqldatareader rdr = cmd.executereader(); while (rdr.read()) { user = new user { userid = (int)rdr["userid"], username = (string)rdr["username"], password = (string)rdr["password"], passwordsalt = (string)rdr["passwordsalt"], money = (int)rdr["money"], farmid = (int)rdr["farmid"], farm ?????? }; } if (rdr != null) rdr.close(); } grab { } } homecoming user; }
my guess have kind of join, right? i'm still query-newbie have patience me please:)
i dont want utilize linq!
thanks!
add bring together sql query below
string sql = "select * users bring together farm on farm.farmid = users.farmid username = @username";
then create instance of farm
, assign user.farm
within while (rdr.read())
block
while (rdr.read()) { user = new user { userid = (int)rdr["userid"], username = (string)rdr["username"], password = (string)rdr["password"], passwordsalt = (string)rdr["passwordsalt"], money = (int)rdr["money"], farmid = (int)rdr["farmid"] }; farm farm = new farm(); farm.farmid = (int)rdr["farmid"]; farm.created = (datetime)rdr["created"]; farm.age = (int)rdr["age"]; user.farm = farm; }
c# mysql sql asp.net-mvc ado.net
No comments:
Post a Comment