使用NSun快速开发ORM在3.5的便捷之关系生成

 

    基上一篇使用NSun快速开发ORM在3.5中的便捷,进行实际代码生成。(这里只对ORM查询进行生成使用,更多的添加修改待完善)

 

关系表示映射。

首先连接所对应数据库,选择需要生成的表进行映射,关系表1和关系表2以及两个表对应的关系字段,还要选择两表之间的关系。暂时没做多对多的关系。

 

Phone 手机

School 学生

Student 学校

3张表体现的是一对多,多对一,一对一的关系。

1.手机和学生是一对一的关系 这里表现为学生phoneid外键对应手机id

2.学生和学校是多对一的关系

3.学校和学生是一对多的关系

 

一对多添加(会自动组建多对一的关系):

多对一添加(同样会自动建立一对多关系):

 

一对一添加(这里需要选择所选关系表1对应字段是否是主键,如果是则需要勾上IsPK选项,同时也会生成一组一对一关系):

 

完成添加后会生成一个扩展方法类方便调用得到对因关系表的内容:

当然也是使用NSun内部方法来调用查询实现的。

 

public static class SchoolExtensionMethods
    {
        
public static List<StudentInfo> Students(this SchoolInfo info)
        {
            
return DBFactory.dbStudent.SelectToIList(DBFactory.dbStudent.GetSelectSqlSection().Where(StudentInfo.__schoolid == info.Id));
        } 
    }

    
public static class StudentExtensionMethods
    {

        
public static SchoolInfo School(this StudentInfo info)
        {
            
return DBFactory.dbSchool.SelectToEntity(info.Schoolid);
        }

        
public static PhoneInfo Phone(this StudentInfo info)
        {
            
return DBFactory.dbPhone.SelectToEntity(info.Phoneid);
        }
    }

 

    
public static class PhoneExtensionMethods
    {
        
public static StudentInfo Student(this PhoneInfo info)
        {
            
return DBFactory.dbStudent.SelectToEntity(DBFactory.dbStudent.GetSelectSqlSection().Where(StudentInfo.__phoneid == info.Id));
        }

    }

 

 

 
  测试:调用通过扩展方法轻松找到对应关系

 

   

       PhoneInfo ph = new PhoneInfo();

            ph.Name 
= 34234234;

            DBFactory.dbPhone.Save(ph);

            SchoolInfo sch 
= new SchoolInfo();

            sch.Name 
= "中山";

            DBFactory.dbSchool.Save(sch);

            StudentInfo stu 
= new StudentInfo();

            stu.Name 
= "ada";

            stu.Phoneid 
= 2;

            stu.Schoolid 
= 1;

            DBFactory.dbStudent.Save(stu); 

            SchoolInfo sc 
= DBFactory.dbSchool.SelectToEntity(1);

            
foreach (var item in sc.Students())
            {
                Console.WriteLine(item.Name);
            }

            StudentInfo st 
= DBFactory.dbStudent.SelectToEntity(1);

            Console.WriteLine(st.Phone().Name);

            Console.WriteLine(st.School().Name);

            PhoneInfo p1 
= DBFactory.dbPhone.SelectToEntity(2);

            Console.WriteLine(p1.Student().Name);

 

 


 

 

     以上使用类库为最新发布的NSunV1.5.2详见使用NSun快速开发NSunV1.5.2发布

    

    实例下载:NSunORM实例(内附数据库文件)

    工具下载:NSunV1.5.2EntityORM生成工具

    类库下载:核心类库(NSun1.5.2)

 

    

    

posted @ 2010-05-24 21:44  Dacey  Views(1547)  Comments(5Edit  收藏  举报