LinQ for MongoDB

请先参看 MongoDB学习笔记(四) 用MongoDB的文档结构描述数据关系

Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MongoDB;
using MongoDB.Configuration;
namespace Mongodb
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        //链接字符串 
        private string connectionString = "mongodb://localhost";
        //数据库名 
        private string databaseName = "myDatabase";
        //集合名 
        string collectionName = "myLinqCollection";
        //定义Mongo服务 
        Mongo mongo;
        MongoDatabase mDatabase;
        MongoCollection<Student> mCollection;
        public MainWindow()
        {
            InitializeComponent();
            mongo = getMongo();
            //获取databaseName对应的数据库,不存在则自动创建  
            mDatabase = mongo.GetDatabase(databaseName) as MongoDatabase;
            mCollection = mDatabase.GetCollection<Student>(collectionName) as MongoCollection<Student>;
            mongo.Connect();
            readVal();
        }
        ~MainWindow()
        {
            mongo.Disconnect();
        }

        private Mongo getMongo()
        {
            var config = new MongoConfigurationBuilder();
            config.Mapping(mapping =>
            {
                mapping.DefaultProfile(porfile =>
                {
                    porfile.SubClassesAre(t => t.IsSubclassOf(typeof(Student)));
                });
                mapping.Map<Student>();
            });
            config.ConnectionString(connectionString);
            return new Mongo(config.BuildConfiguration());

        }

        private void rb_add_Click(object sender, RoutedEventArgs e)
        {
            tb_ID.IsEnabled = true;
            tb_Name.IsEnabled = true;
            tb_mail.IsEnabled = true;
            tb_age.IsEnabled = true;
        }

        private void rb_update_Click(object sender, RoutedEventArgs e)
        {
            tb_ID.IsEnabled = true;
            tb_Name.IsEnabled = true;
            tb_mail.IsEnabled = true;
            tb_age.IsEnabled = true;
        }

        private void rb_del_Click(object sender, RoutedEventArgs e)
        {
            tb_ID.IsEnabled = true;
            tb_Name.IsEnabled = false;
            tb_mail.IsEnabled = false;
            tb_age.IsEnabled = false;
        }


        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (cb_search.IsChecked.HasValue && cb_search.IsChecked.Value)
            {
                var allresult = mCollection.Linq().Where(n => n.name.Contains(tb_search.Text.Trim()) ).OrderBy(args => args.id)
                    ;
                if (allresult.Count() > 0)
                    readVal(allresult);
            }
            else
            {
                if (rb_add.IsChecked.HasValue && rb_add.IsChecked.Value)
                {
                    var Val = mCollection.Linq().Where(n => n.id == int.Parse(tb_ID.Text.Trim()));
                    if (Val != null && Val.Count() == 0)
                    {

                        Student stu = new Student();
                        stu.id = int.Parse(tb_ID.Text.Trim());
                        stu.name = tb_Name.Text.Trim();
                        stu.Detail = new Detail();
                        stu.Detail.age = int.Parse(tb_age.Text.Trim());
                        stu.Detail.email = tb_mail.Text.Trim();
                        mCollection.Insert(stu);
                    }
                    else
                    {
                        MessageBox.Show("已经存在相同ID");
                    }
                }
                if (rb_update.IsChecked.HasValue && rb_update.IsChecked.Value)
                {
                    var Val = mCollection.Linq().Where(n => n.id == int.Parse(tb_ID.Text.Trim())).FirstOrDefault();
                    if (Val != null)
                    {
                        Student upVal = new Student();
                        upVal.id = Val.id;
                        upVal.name = tb_Name.Text.Trim();
                        upVal.Detail = new Detail();
                        upVal.Detail.age = int.Parse(tb_age.Text.Trim());
                        upVal.Detail.email = tb_mail.Text.Trim();
                        mCollection.FindAndModify(upVal, Val);
                    }
                }
                if (rb_del.IsChecked.HasValue && rb_del.IsChecked.Value)
                {
                    mCollection.Remove(n => n.id == int.Parse(tb_ID.Text.Trim()));
                }
                readVal();
            }
        }

        private void readVal()
        {
            IQueryable<Student> allResult = mCollection.Linq().OrderBy(args => args.id);
            readVal(allResult);
        }

        private void readVal(IEnumerable<Student> allResult)
        {
            lb_result.Items.Clear();
            foreach (Student item in allResult.ToList<Student>())
            {

                string info = string.Format("id={0},name={1},age={2},mail={3}", item.id, item.name, item.Detail.age, item.Detail.email);
                lb_result.Items.Add(info);
            }
        }
    }
    public class Student
    {
        public int id { get; set; }
        public string name { get; set; }
        private Detail detail;
        public Detail Detail
        {
            get { return detail; }
            set { detail = value; }
        }
    }
    public class Detail
    {
        public int age { get; set; }
        public string email { get; set; }
    }
}


Xaml

<Window
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" x:Class="Mongodb.MainWindow"
        Title="MainWindow" Height="350" Width="374">
    <Grid>
    	<TextBlock HorizontalAlignment="Left" Margin="72,49,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="30.557"><Run Language="zh-cn" Text="ID:"/></TextBlock>
    	<TextBox x:Name="tb_ID" Margin="106.557,43,0,0" TextWrapping="Wrap" Text="1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="214.487"/>
    	<TextBlock HorizontalAlignment="Left" Margin="49,68.836,0,0" TextWrapping="Wrap" VerticalAlignment="Top"><Run Language="zh-cn" Text="Name:"/></TextBlock>
    	<TextBox x:Name="tb_Name" Margin="106.557,68.836,0,0" TextWrapping="Wrap" Text="seelingzheng" VerticalAlignment="Top" HorizontalAlignment="Left" Width="214.487"/>
    	<Button Content="OK" Click="Button_Click"  HorizontalAlignment="Right" Margin="0,0,28,132.163" Width="75" VerticalAlignment="Bottom" d:LayoutOverrides="HorizontalAlignment"/>
    	<RadioButton x:Name="rb_add" Click="rb_add_Click"  Content="Add" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="72,17.163,0,0" IsChecked="True"/>
    	<RadioButton x:Name="rb_update" Click="rb_update_Click"  Content="update" Margin="131.853,17.163,0,0" VerticalAlignment="Top" HorizontalAlignment="Left"/>
    	<RadioButton x:Name="rb_del" Click="rb_del_Click"  Content="del" Margin="211.853,17.163,0,0" VerticalAlignment="Top" HorizontalAlignment="Left"/>
    	<ListBox x:Name="lb_result"  Height="100" Margin="23,0,0,15" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="307"/>
    	<TextBlock HorizontalAlignment="Left" Margin="59,98,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="30.557"><Run Language="zh-cn" Text="Age:"/></TextBlock>
    	<TextBox x:Name="tb_age" Margin="106.557,92,0,0" TextWrapping="Wrap" Text="1" VerticalAlignment="Top" HorizontalAlignment="Left" Width="214.487"/>
    	<TextBlock HorizontalAlignment="Left" Margin="52,117.836,0,0" TextWrapping="Wrap" VerticalAlignment="Top"><Run Language="zh-cn" Text="Email:"/></TextBlock>
    	<TextBox x:Name="tb_mail" Margin="106.557,117.836,0,0" TextWrapping="Wrap" Text="test@qq.com" VerticalAlignment="Top" HorizontalAlignment="Left" Width="214.487"/>
    	<TextBox x:Name="tb_search" Margin="115.02,0,0,132.163" TextWrapping="Wrap" VerticalAlignment="Bottom" HorizontalAlignment="Left" Width="130.513"/>
    	<CheckBox x:Name="cb_search" Content="search" HorizontalAlignment="Left" Margin="38,0,0,135.163" VerticalAlignment="Bottom"/>
        
    </Grid>
</Window>


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

seelingzheng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值