c# - How can I update my database from my controller for values already listed in ASP.NET? -
my application fetching stock data yahoo finance , storing database. whenever new stock, can add database, having trouble editing existing entries. msft example, in database.
here controller:
// get: stockinfo public actionresult index() { string csvdata; string symbols = "msft"; using (webclient web = new webclient()) { csvdata = web.downloadstring("http://finance.yahoo.com/d/quotes/csv?s=" + symbols + "&f=sa2l1t8c1p2j1rye"); stockinfo stocks = yahoofinance.parse(csvdata); // place fetched data model properties // check if in database stockinfo temp = db.stockinfo.find(stocks.symbol); if (temp == null) // create new entry { if (modelstate.isvalid) { db.stockinfo.add(stocks); db.savechanges(); } } else // edit existing entry { // not done yet } } return view(db.stockinfo.tolist()); }
and here model:
public class stockinfo { [key] public string symbol { get; set; } public decimal averagevolume { get; set; } public decimal lasttradeprice { get; set; } public decimal oneyeartarget { get; set; } public decimal change { get; set; } public string changepercent { get; set; } public string marketcap { get; set; } public decimal priceearningsratio { get; set; } public string dividendyield { get; set; } public decimal earningspershare { get; set; } }
i've tried other solutions on stack overflow involving entity state don't seem working me. thank in advance!!
try following code:
else // edit existing entry { // update temp fields here stocks values temp.averagevolume = stocks.averagevolume; temp.lasttradeprice = stocks.lasttradeprice; temp.oneyeartarget = stocks.oneyeartarget; temp.change = stocks.change; temp.changepercent = stocks.changepercent; temp.marketcap = stocks.marketcap; temp.priceearningsratio = stocks.priceearningsratio; temp.dividendyield = stocks.dividendyield; temp.earningspershare = stocks.earningspershare; db.entry(temp).state = entitystate.modified; db.savechanges(); }
Comments
Post a Comment