zoukankan      html  css  js  c++  java
  • Entity Framework学习四:查询和建模进阶

    1.复杂类型(complex types)

        复杂类型是定义Entity列集合的类,没有主键,不直接映射表。在类中定义复杂类型时,必须为非集合类型。

       看实例,我们在前面几篇学习中的实例中添加Address类

    public class Address
        {
            public string Street { get; set; }
            public string City { get; set; }
            public string State { get; set; }
        }
    
        public class AddressMap : ComplexTypeConfiguration<Address>
        {
            public AddressMap()
            {
                Property(p => p.Street)
                    .HasColumnName("Street");
                Property(p => p.City)
                    .HasColumnName("City");
                Ignore(p => p.State);//忽略State对表列的映射,在数据库表中不会有此列
            }
        }

    在People类中添加属性。注意一点的是添加属性后必须在构造函数中初始化,否则会异常

    public Address Address { get; set; }//必须为集合属性
    public Person()
            {
                Phones = new HashSet<Phone>();
                CompanyList = new HashSet<Company>();
                Address = new Address();//必须初始化
            }

    记得在Context中注册AddressMap

    modelBuilder.Configurations.Add(new AddressMap());

    那么我们在数据中怎么对应?我们需要在People表中增加Street列和City列,结构如下

    image

    2.使用枚举类型

    在程序中使用枚举类型来对数据库中数字进行表示,能够让程序有更好的可读性。我们定义一个PersonState枚举类型

    public enum PersonState
        {
            Active,
            IsActive,
            Unknow
        }

    在前面程序的People类中添加代码:

    public class Person
        {     
    
            
    public PersonState PersonState { get; set
    ; }//新增
    
        }

    还有一步要做的就是要在前面People表中增加PersonState字段,定义为int类型。

    image

    下面我们就可以利用枚举类型了,看示例:

    var query = context.People.Where(p => p.PersonState == PersonState.Active);
                foreach(var person in query)
                {
                    Console.WriteLine(person.LastName);
                }
  • 相关阅读:
    Format用法总汇
    packed record与record区别
    将实数取整函数
    取鼠标所在位置对应的窗口句柄
    Delphi中优秀的字符串分割函数
    Jscript中的FSO对象模式
    关于.NET开发中遇到的一个验证视图状态Mac失败的解决方法随笔
    如何延长电脑硬盘的使用寿命
    如何避免U盘中毒
    如何优化Windows XP系统来加快网速
  • 原文地址:https://www.cnblogs.com/zjmsky/p/4827865.html
Copyright © 2011-2022 走看看