silverlight 通过WCF与LinQ对数据库进行操作2
本文主要演示了在silverlight中如何通过WCF和LinQ语句对数据库进行简单操作,这是第二部分,第一部分为:silverlight 通过WCF与LinQ对数据库进行操作1
接下来在MainPage中再拖一个button控件命名为btnDelete,用于触发删除事件。在Service1.svc中加入删除方法:
public void Delete(string pName) { DataClasses1DataContext dc = new DataClasses1DataContext(); var per = from s in dc.person where s.name == pName select s; if (per != null) { dc.person.DeleteAllOnSubmit(per); dc.SubmitChanges(); } }
双击删除按钮,进入后台,输入代码:
private void btnDelete_Click(object sender, RoutedEventArgs e) { string name = textBox1.Text; proxy.DeleteAsync(name); }
调用该方法后会删除表中所有name值与textbox1中输入的文本名称相同的数据。
同理,修改数据的代码为:
public void Update(string pName, int pAge) { DataClasses1DataContext dc = new DataClasses1DataContext(); var per = from s in dc.person where s.name == pName select s; foreach (person p in per) { p.age = pAge; } dc.SubmitChanges(); }
private void btnUpdate_Click(object sender, RoutedEventArgs e) { string name = textBox1.Text; int age = Convert.ToInt32(textBox2.Text); proxy.UpdateAsync(name, age); }
在文本框中分别输入名称和年龄,会将数据库中相同名称的记录的年龄改为输入的年龄。
现在在MainPage中拖入一个DateGrid用于显示数据库中的数据:
<sdk:DataGrid AutoGenerateColumns="False" Height="225" HorizontalAlignment="Left" Margin="284,39,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="282" > <sdk:DataGrid.Columns> <sdk:DataGridTextColumn Header="ID" Binding="{Binding id}" Width="60"></sdk:DataGridTextColumn> <sdk:DataGridTextColumn Header="姓名" Binding="{Binding name}" Width="80"></sdk:DataGridTextColumn> <sdk:DataGridTextColumn Header="年龄" Binding="{Binding age}" Width="85"></sdk:DataGridTextColumn> </sdk:DataGrid.Columns> </sdk:DataGrid>
Service1.svc中通过查询语句返回表中记录集合:
public List<person> GetData() { List<person> list = new List<person>(); DataClasses1DataContext dc = new DataClasses1DataContext(); var query = from p in dc.person select p; return query.ToList<person>(); }
客户端通过Completed方法得到集合,并赋给dataGrid1.ItemSource:
void proxy_GetDataCompleted(object sender, ServiceReference1.GetDataCompletedEventArgs e) { dataGrid1.ItemsSource = e.Result; }
现在就可以对数据库中的数据进行简单的增删改查了,最后效果图如下:
最后代码为:https://files.cnblogs.com/infly123/SilverlightApplication8f.rar