2016-04-25 75 views
0

問題我正在嘗試write LINQ to Add or Update但對於我EntityState.Modified不起作用。面對添加或更新方案

看看我的代碼,讓我知道如果你看到任何錯誤。 只有新記錄插入工作,但更新不起作用。 我正在使用EF 6.0。

dbContext _context = new dbContext();    
string userName = //getting this value from somewhere else; 
string userRoleNo = //getting this value from somewhere else; 
Student student = new Student 
{ 
    userName = userName, 
    userRoleNo = userRoleNo, 
    Date = DateTime.Now 
}; 
bool exist = _context.Students.Any(x => x.UserId == new Guid(userId)); 
if (exist) 
    _context.Entry(Student).State = EntityState.Modified;    
else 
    _context.Students.Add(student); 

_context.SaveChanges(); 
+0

什麼存在的價值?代碼是否落入其他部分? – Haris

+0

查看這種比較GUIDs的方法:http://stackoverflow.com/questions/5725044/how-do-i-perform-a-case-insensitive-compare-of-guids-with-linq – DrinkBird

+0

哈里存在真實,代碼如果部分屬於這種情況_context.Entry(Student).State = EntityState.Modified;被執行但是在表中沒有任何東西 – simbada

回答

0

我想這應該是

db.Entry(student).State = EntityState.Modified 

,而不是

db.Entry(Student).State = EntityState.Modified 
0

只添加,如果它是一個新學生。如果沒有,EF會跟蹤你的變化。這樣,您可以離開追蹤並附加到EF。

dbContext _context = new dbContext();  
var student = _context.Students.FirstOrDefault(x => x.UserId == new Guid(userId)); // Get the existing student. 
bool exists = true; 
if(student == null){ 
    student = new Student(); 
    exists = false; 
} 

string userName = //getting this value from somewhere else; 
string userRoleNo = //getting this value from somewhere else; 
student.userName = userName; // Do you really want to reset this? 
student.userRoleNo = userRoleNo; 
student.Date = DateTime.Now: 

if(!exists){ 
    _context.Students.Add(student); 
} 
_context.SaveChanges(); 

連接,當你不從上下文獲取項目時,才需要EntityState.Modified。但是在這種情況下,它會改爲取回該項目。

0

這樣做的正確的方式將

using(_context = new dbContext()){ //This will dispose the context   
string userName = //getting this value from somewhere else; 
string userRoleNo = //getting this value from somewhere else; 
Student student = _context.Students.FirstOrDefault(x => x.UserId == new Guid(userId)); 


if (student != null) 
{ 
    student.userName = userName; 
    student.userRoleNo = userRoleNo; 
    student.Date = DateTime.Now ; 
    _context.Entry(student).State = EntityState.Modified;  
}   
else 
{ 
     student = new Student() { 
     userName = userName, 
     userRoleNo = userRoleNo, 
     Date = DateTime.Now 
    }; 
    _context.Students.Add(student); 
} 
_context.SaveChanges(); 
};