entity framework选择查询
我正在使用Entity Framework
制作一个简单的插入,更新,删除,选择数据的应用程序
我已经插入,删除并选择了所有数据。
现在我想选择具有两个字段的filter的where条件
例如:我有桌子
userid username password email
现在需要选择例如where email = "" and password = ""
我知道如何在SQL中编写查询但没有entity framework
线索。
还需要将此结果存储在数据表和循环解决方案中,以用于学习目的。
这可以帮助许多初学者
使用具有lambda表达式的Linq To Entities:
var result = dBContext.Account.Where(a=> a.email == "" && a.password =="").ToList();
使用Linq To Entities的方式不那么花哨:
var result = (from a in dBContext.Account where a.email == "" && a.password =="" select a).ToList();
Lambda表达式大多数时候都在使用。 有些人发现lambda的可读性较差。 我认为这更多的是个人品味,取决于你的背景。
编辑:
在设置Entitiy框架EDMX或代码优先类时,dbContext应替换为您为dbContext / Entities提供的名称。
帐户应替换为您的表/实体的名称
要循环和编辑结果,您可以执行以下操作:
foreach(var account in results) { //do something with the properties account.email = "test@updated.com" } //store the changes again in the db dbContext.SaveChanges();
使用linq ex:
List result = dbContext.Users.Where(o=> o.email == "" && o.password=="").ToList(); foreach(User u in result) { // do stuff } User u = new User(); u.Email = "mail@mail.com"; dbContext.Users.Add(u); dbContext.Save(); //I think its Save()..
必须使用Linq查询之类的
var data= dBContext.Account.Where(a=> a.email == "" && a.password =="").ToList();
.ToList()
将提供您的where条件或filter下的整个数据。 现在,您可以返回DataTable
并根据您的DataTable
值轻松应用condtion。
DataTable tempData = (DataTable)grdRecords.DataSource; var query = from r in tempData.AsEnumerable() where r.Field("UserName") != "TestUsername" && r.Field ("Password") != "TestPassword" select r; DataTable newDT = query.CopyToDataTable();
使用linq查询如下
IList Users = dbContext.Users.Where(x=> x.email == "" && x.password=="").ToList();
然后,如果你想转换成DataTable,只需调用以下generics方法做转换
public DataTable ToDataTable(IList data)// T is any generic type { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T)); DataTable table = new DataTable(); for (int i = 0; i < props.Count; i++) { PropertyDescriptor prop = props[i]; table.Columns.Add(prop.Name, prop.PropertyType); } object[] values = new object[props.Count]; foreach (T item in data) { for (int i = 0; i < values.Length; i++) { values[i] = props[i].GetValue(item); } table.Rows.Add(values); } return table; }
你可以试试这个
databasenameEntities db = new databasenameEntities (); tablename exist= db.tablename.where(p=>p.email=="txtemail.text" && p.password=="txtpassword.text"); if(exist.count>0) { txtuserid.text=Convert.toInt32(exist.userid); txtusername.Text=exist.username; .... ..... db.saveChanges(); }
希望这可能有帮助。