数据库模型

这个基本上是浓缩 Jerry Tom博客的内容,作为参考http://www.cnblogs.com/mbailing/archive/2012/07/31/2616779.html

说明以后再写。

城市实体类

public partial class city

{

    public int ID { get; set; }

    [MaxLength(100)]

    [RegularExpression(@"^[a-zA-Z''-'\s]{1,40}$")]

    public string Name { get; set; }

    public string CountryCode { get; set; }

    public string District { get; set; }

    public int Population { get; set; }

    public virtual country country { get; set; }

    //这个field临时添加,并没有在数据库中映射

    [CustomValidation(typeof(BusinessValidations), "DescriptionRules")]

    public string Description { get; set; }

}

国家实体类

public partial class country

   {

       public country()

       {

           this.cities = new List<city>();

       }

 

       public string Code { get; set; }

       public string Name { get; set; }

       public string Continent { get; set; }

       public string Region { get; set; }

       public float SurfaceArea { get; set; }

       public Nullable<short> IndepYear { get; set; }

       public int Population { get; set; }

       public Nullable<float> LifeExpectancy { get; set; }

       public Nullable<float> GNP { get; set; }

       public Nullable<float> GNPOld { get; set; }

       public string LocalName { get; set; }

       public string GovernmentForm { get; set; }

       public string HeadOfState { get; set; }

       public Nullable<int> Capital { get; set; }

       public string Code2 { get; set; }

       public virtual ICollection<city> cities { get; set; }

   }

 

自定义验证类

using System;

using System.Collections.Generic;

using System.ComponentModel.DataAnnotations;

using System.Linq;

using System.Text;

 

namespace EFEntity.Validation

{

    public static class BusinessValidations

    {

        public static ValidationResult DescriptionRules(string value)

        {

            var errors = new System.Text.StringBuilder();

            if (value != null)

            {

                var description = value as string;

                if (description.Contains("!"))

                {

                    errors.AppendLine("Description should not contain '!'.");

                }

                if (description.Contains(":)") || description.Contains(":("))

                {

                    errors.AppendLine("Description should not contain emotions.");

                }

            }

            if (errors.Length > 0)

                return new ValidationResult(errors.ToString());

            else

                return ValidationResult.Success;

        }

    }

}

各种静态方法操作全在Controller.cs文件

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using EFEntity.Models;

 

namespace EFEntity

{

    class Controller

    {

        /// <summary>

        /// 添加一个实体

        /// </summary>

        /// <returns></returns>

        public static int AddEntity()

        {

            using (var context = new worldContext())

            {

                var newCity = new city

                    {

 

                        CountryCode = "CHN",

                        District = "Guangdong",

                        Name = "珠海",

                        Population = 10000000

                    };

                context.cities.Add(newCity);

                return context.SaveChanges();

            }

        }

 

        /// <summary>

        /// 同时添加和修改实体

        /// </summary>

        /// <returns></returns>

        public static int MakeMultipleChanges()

        {

            using (var context = new worldContext())

            {

                var niagaraFalls = new city

                    {

                        Name = "Niagara Falls",

                        CountryCode = "USA",

                        District = "California",

                        Population = 12232

                    };

                context.cities.Add(niagaraFalls);

                var query = (from d in context.cities

                             where d.Name == "广州"

                             select d).First();

 

                query.Name = "惠州";

                return context.SaveChanges();

 

 

            }

        }

 

        /// <summary>

        /// 删除一个实体

        /// </summary>

        /// <returns></returns>

        public static int DeleteCity()

        {

            using (var context = new worldContext())

            {

                var oldCity = (from d in context.cities

                               where d.Name == "珠海"

                               select d).Single();

                context.cities.Remove(oldCity);

                return context.SaveChanges();

            }

        }

 

        /// <summary>

        /// 级联删除一个实体(国家)和它相关联的从表实体(城市)

        /// </summary>

        /// <returns></returns>

        public static int DeleteUsaAndCities()

        {

            using (var context = new worldContext())

            {

                var countryUSA = (from d in context.countries

                                  where d.Name == "United States"

                                  select d).Single();

                context.Entry(countryUSA).Collection(d => d.cities).Load();

                context.countries.Remove(countryUSA);

                return context.SaveChanges();

            }

 

        }

 

        /// <summary>

        /// 找到返回一个实体,找不到添加并返回一个实体

        /// </summary>

        public static void FindOrAddCity()

        {

            using (var context = new worldContext())

            {

 

                var newCity = context.cities.FirstOrDefault(p => p.Name == "湛江");

 

                if (newCity == null)

                {

                    newCity = context.cities.Add(new city

                    {

                        Name = "湛江",

                        CountryCode = "CHN",

                        District = "Guangdong",

                        Population = 100

                    });

                    context.SaveChanges();

                }

 

                Console.WriteLine("增加或找到的城市为:" + newCity.Name);

            }

        }

 

        /// <summary>

        /// 创建从表实体,并依附到主表实体,建立关联。

        /// </summary>

        /// <returns></returns>

        public static int NewRelationData()

        {

            using (var context = new worldContext())

            {

                var newcity = new city

                    {

                        Name = "随便什么城市",

                        CountryCode = "CHN", //这个属性值后来还是变成为ZWE,

                        //说明我们在Country加载后覆盖了这个值。

                        District = "Guangdong",

                        Population = 1231232

                    };

                context.cities.Add(newcity);

 

                var countryChina = (from d in context.countries

                                    where d.Code == "ZWE"

                                    select d).Single();

                countryChina.cities.Add(newcity);

                return context.SaveChanges();

            }

        }

 

        /// <summary>

        /// 修改从表实体的依附关系

        /// </summary>

        /// <returns></returns>

        public static int ChangeRelationData()

        {

            using (var context = new worldContext())

            {

                var oldCity = (from c in context.cities

                               where c.Name == "湛江"

                               select c).Single();

                var oldCountry = (from d in context.countries

                                  where d.Code == "ZWE"

                                  select d).Single();

                oldCity.country = oldCountry;

                return context.SaveChanges();

            }

        }

 

        /// <summary>

        /// 检查修改状态

        /// </summary>

        public static void ManualDetectChanges()

        {

            using (var context = new worldContext())

            {

                context.Configuration.AutoDetectChangesEnabled = false;

                var countryAFG = (from d in context.countries

                                  where d.Name == "Afghanistan"

                                  select d).Single();

                countryAFG.SurfaceArea = 1000000;

                Console.WriteLine("Before DetectChanges: {0}", context.Entry(countryAFG).State);

                context.ChangeTracker.DetectChanges();

                Console.WriteLine("After DetectChanges: {0}", context.Entry(countryAFG).State);

 

            }

        }

 

   

 

        /// <summary>

        /// 验证通用方法

        /// </summary>

        /// <typeparam name="T"></typeparam>

        /// <param name="input"></param>

        public static void ConsoleValidateResult<T>(T input) where T : class

        {

            using (var context = new worldContext())

            {

                if (context.Entry(input).GetValidationResult().IsValid)

                {

                    Console.WriteLine("----Valid 验证通过!");

                }

                else

                {

                    Console.WriteLine("----Invalid 验证不通过!");

                }

            }

        }

 

        /// <summary>

        /// 验证实体

        /// </summary>

        public static void ValidateCity()

        {

            //-------------------------------------

            Console.WriteLine("\n验证最大长度");

            ConsoleValidateResult<city>(

                new city

                    {

                        Name = "3412ieiorjteiwjlkrj0943u5094tiroejiktjfgkjfdklsjgdsfddfgfdgfdlksdfs",

                        CountryCode = "CHN",

                        District = "Guangdong",

                        Population = 122

 

                    });

            //-------------------------------------

            Console.WriteLine("\n验证正则表达式");

            ConsoleValidateResult<city>(

                new city

                    {

                        Name = "BeiJingCity",

                        CountryCode = "CHN",

                        District = "直辖市",

                        Population = 100

                    });

 

            //-------------------------------------

            Console.WriteLine("\n验证自定义的规则,这里是Description不能有某些字符串");

            ConsoleValidateResult<city>(

                new city

                    {

                        Name = "Guangzhou", //这里不能是汉字,要不然通不过正则表达式验证

                        CountryCode = "CHN",

                        District = "Guangdong",

                        Population = 100,

                        Description = "This is the description."

                    });

        }

        

        /// <summary>

        /// 于请求中验证属性(Validating Individual Properties on Demand) 

        /// </summary>

        public static void ValidatePropertyOnDemand()

        {

            var cityItem = new city

                {

                    Name = "Beijing",

                    CountryCode = "CHN",

                    District = "直辖市",

                    Population = 100,

                    Description = "我爱北京天安门,Shit!"

 

                };

            using (var context = new worldContext())

            {

                var errors = context.Entry(cityItem).Property(p => p.Description).GetValidationErrors();

                Console.WriteLine();

                Console.WriteLine("#Description 验证错误; {0}",errors.Count());

            }

        }

    }

}

Entity Framework -- 添加,删除,修改,关系依附,关系摘除,验证操作的更多相关文章

  1. Entity framework 绑定到Datagridview的添加删除修改

    Entity framework 绑定到Datagridview的添加删除修改 using System; using System.Collections.Generic; using System ...

  2. Entity Framework Code First主外键关系映射约定

    本篇随笔目录: 1.外键列名默认约定 2.一对多关系 3.一对一关系 4.多对多关系 5.一对多自反关系 6.多对多自反关系 在关系数据库中,不同表之间往往不是全部都单独存在,而是相互存在关联的.两个 ...

  3. 【极力分享】[C#/.NET]Entity Framework(EF) Code First 多对多关系的实体增,删,改,查操作全程详细示例【转载自https://segmentfault.com/a/1190000004152660】

      [C#/.NET]Entity Framework(EF) Code First 多对多关系的实体增,删,改,查操作全程详细示例 本文我们来学习一下在Entity Framework中使用Cont ...

  4. [C#/.NET]Entity Framework(EF) Code First 多对多关系的实体增,删,改,查操作全程详细示例

    本文我们来学习一下在Entity Framework中使用Context删除多对多关系的实体是如何来实现的.我们将以一个具体的控制台小实例来了解和学习整个实现Entity Framework 多对多关 ...

  5. SQL语句添加删除修改字段及一些表与字段的基本操作

    用SQL语句添加删除修改字段 1.增加字段     alter table docdsp    add dspcode char(200)2.删除字段     ALTER TABLE table_NA ...

  6. JavaScript学习 - 基础(八) - DOM 节点 添加/删除/修改/属性值操作

    html代码: <!--添加/删除/修改 --> <div id="a1"> <button id="a2" onclick=&q ...

  7. JTree 添加 , 删除, 修改

    package com.swing.demo; import java.awt.BorderLayout; import java.awt.Container; import java.awt.eve ...

  8. 用SQL语句添加删除修改字段、一些表与字段的基本操作、数据库备份等

    用SQL语句添加删除修改字段 1.增加字段 alter table docdsp add dspcode char(200) 2.删除字段 ALTER TABLE table_NAME DROP CO ...

  9. SQL语句添加删除修改字段[sql server 2000/2005]

    用SQL语句添加删除修改字段1.增加字段     alter table docdsp    add dspcodechar(200)2.删除字段     ALTER TABLE table_NAME ...

  10. SQL语句添加删除修改字段

    用SQL语句添加删除修改字段1.增加字段     alter table docdsp    add dspcodechar(200)2.删除字段     ALTER TABLE table_NAME ...

随机推荐

  1. uvalive 3231

    3231 - Fair ShareAsia - Seoul - 2004/2005You are given N processors and M jobs to be processed. Two ...

  2. 刽子手游戏(Hangman Judge, UVa 489)

    刽子手游戏其实是一款猜单词游戏,游戏规则是这样的:计算机想一个单词让你猜,你每次可以猜一个字母.如果单词里有那个字母,所有该字母会显示出来:如果没有那个字母,则计算机会在一幅“刽子手”画上填一笔.这幅 ...

  3. 【6】Django视图函数

    治大国若烹小鲜.以道莅天下 --老子<道德经> 本节内容 Django web项目的运行流程分析 视图处理函数的定义 多视图处理函数及接收参数 1. web项目运行流程分析 通常情况下,完 ...

  4. 【Codeforces 1106C】Lunar New Year and Number Division

    [链接] 我是链接,点我呀:) [题意] 题意 [题解] 看了下样例解释就懂了... 每次选择最大最小的两个组合 然后加起来.. [代码] import java.io.IOException; im ...

  5. sql中对数值四舍五入取小数点后两位数字

    用:cast(value as decimal(10,2)) 来实现.

  6. nyoj_17_单调递增最长子序列_201403121516

    单调递增最长子序列 时间限制:3000 ms  |  内存限制:65535 KB 难度:4   描述 求一个字符串的最长递增子序列的长度如:dabdbf最长递增子序列就是abdf,长度为4   输入 ...

  7. VMware镜像文件下载

    VMware镜像文件下载 http://blog.sina.com.cn/s/blog_517c21c00102x5ja.html  貌似Centos 6不能下载啊: 其他的没有测试:

  8. string 和 vector 初探

    标准库类型 string string 表示可变长的字符序列.是C++标准库类型的一部分,拥有很多优秀的性能. 定义 string 对象时如未人为初始化编译器会默认初始化为空字符串. string 对 ...

  9. 飘逸的python - 实现一个极简的优先队列

    一个队列至少满足2个方法,put和get. 借助最小堆来实现. 这里按"值越大优先级越高"的顺序. #coding=utf-8 from heapq import heappush ...

  10. 浅谈 System.Decimal 结构

    引言 我们知道,Microsoft .NET Framework 中的 System.Decimal 结构(在 C# 语言中等价于 decimal keyword)用来表示十进制数,范围从 -(296 ...