2012-06-07 73 views
-2

在實體框架中,當您提交新項目時,它不會根據數據庫更新其ID。例如:獲取模型更新Id

public class A { 
    public int Id {get; set;} 
    public DateTime LastUpdateUtc {get; set;} 
} 

現在,當我添加一個新的A到我的倉庫:

A a = new A(); 
a.LastUpdateUtc = DateTime.UtcNow; 
repo.Add(a); 
repo.SaveChange(); 
a.Id; // still == 0 

即使我搜索我的庫中的eleement我得到一個A,但該標識仍然等於0

A a = repo.Asquerable().OrderByDescending(a => a.LastUpdateUtc).First(); 
a.Id; // still == 0 

有人知道我該如何告訴實體框架更新數據庫計算的Id feild?

感謝

+0

是ID列的數據庫或沒有標識列?一個int默認爲0,所以這就是爲什麼它總是0--你沒有設置它。 – Arran

+0

是的,它是我的數據庫中的Id – mathk

回答

0

最終我沒有讓它通過添加attirbute工作:

[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] 
0

實體框架將自動從數據庫中檢索新的自動生成的ID字段,如果你的ID列具有自動編號屬性。你看過數據庫以確保你的ID數據實際上不是0嗎?

0

試試這個,請

public override TR Create<T, TR>(T entity) 
{ 
    string entitySet = GetEntitySetName<T>(); 
    _context.AddObject(entitySet, entity); 
    _context.SaveChanges(); 

    //Returns primaryKey value 
    return (TR)context.CreateEntityKey(entitySet, entity).EntityKeyValues[0].Value;      
} // Where T: entity type, TR: entity PK type 

如果這是確定 - 這裏看看EF Generic Repository get Id from new inserted generic entity

0

而不是

A a = repo.Asquerable().OrderByDescending(a => a.LastUpdateUtc).First(); 
a.Id; 

嘗試

A queryA = repo.Asquerable().OrderByDescending(a => a.LastUpdateUtc); 
queryA.First().Id; 

a在這種情況下是一個實體(未查詢),並不會改變