首页 > 数据库 >在Code first中使用数据库里的视图

在Code first中使用数据库里的视图

时间:2023-05-30 20:15:19浏览次数:67  
标签:Code dbo void vReplyStatus 视图 override public first

一、使用Database.SqlQuery<T>("查询语句"),如:

var query = db.Database.SqlQuery<ReplyStatusViewModel>("SELECT * FROM dbo.vReplyStatus")

然后在vReplyStatus视图的基础上进行各种查询:

var qqo = query.Where(p => p.PrdOrd.Contains("袁"));
var count = qqo.Count();//会出错!-->nullreferenceexception-->因为PrdOrd字段里有null或空值。

改为如下可通过:

var qqo = query.Where(p => p.PrdOrd != null && p.PrdOrd.Contains("袁"));

这样产生的语句是:

SELECT * FROM dbo.vReplyStatus.Where(p => ((p.PrdOrd != null) AndAlso p.PrdOrd.Contains("袁")))

但是在使用到dynamic linq时好像无法把p.ProdOrd != null 加上,dynamic linq产生的语句是:

SELECT * FROM dbo.vReplyStatus.Where(p => p.Planner.Contains("袁")).Union(SELECT * FROM dbo.vReplyStatus.Where(p => p.PrdOrd.Contains("袁"))).Union(SELECT...

这是一个模糊查询语句,在所有的字段中查找包含袁的数据。但是少了!=null 的条件,这样在计数的时候var count = qqo.Count();就会出错。

二、在上下文中加入视图模型

现在使用的是第二种方法,将ReplyStatusViewModel类加入上下文类中,然后在model创建时加入该实体(把视图假装是一个表)。提示数据迁移后,先不要update-database!把迁移文件中的内容注释掉,即把 public override void Up() 和 public override void Down()的内容清空,来进行一次空的迁移,最后更新数据库。

步骤如下:

1、创建类(ReplyStatusViewModel)该类和视图中的字段一一对应。

public class ReplyStatusViewModel
{
        public int ID { get; set; }
        public bool Del { get; set; }
        public decimal? Qty { get; set; }
        public string ReplyStatus { get; set; }
}

2、更改上下文类

public class MyContext : DbContext
{ public MyContext () : base("name=DefaultConnection") { } public DbSet<ReplyStatusViewModel> ReplyStatusViewModel { get; set; }// 映射数据库里的视图 protected override void OnModelCreating(DbModelBuilder modelBuilder) {
// vReplyStatus 就是视图的名字 modelBuilder.Entity<ReplyStatusViewModel>().ToTable("vReplyStatus"); } }

3、添加数据迁移

PM> Add-migration test

会自动显示一个类文件,把上下文里的更改当做创建一个表:

 public partial class test : DbMigration
    {
        public override void Up()
        {
            CreateTable(
                "dbo.ReplyStatusViewModels",
                c => new
                    {
                        ID = c.Int(nullable: false, identity: true),
                        Del = c.Boolean(nullable: false),
                        Qty = c.Decimal(precision: 18, scale: 2),                     
                        ReplyStatus = c.String(),
                    })
                .PrimaryKey(t => t.ID);
            
        }
        
        public override void Down()
        {
           DropTable("dbo.ReplyStatusViewModels");     
        }
    }
}

这里的内容不是我们需要的,如果数据库里还没有视图,可以在up里创建一个视图:

public override void Up()
{
     Sql(@"CREATE VIEW [dbo].[vReplyStatus] AS 
           SELECT     a.ID, ……
      ");        
}
        
public override void Down()
{
     Sql(@"IF  EXISTS 
        (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'dbo.vReplyStatus')) DROP VIEW dbo.vReplyStatus"); }

如果数据库里已有视图,则把内容清空即可:

public override void Up()
{
         
}
        
public override void Down()
{

}
              

添加数据迁移时可以加一个参数:IgnoreChanges,这样Up和Down里自动为空白。

 

最后运行

PM> Update-Database

 

 在Controller里可以像使用其他实体类一样来使用视图了!

public string GetMasterData()
{
  using (var db = new PurchasePlanContext())
  {
     IQueryable<ReplyStatusViewModel> query9 = db.ReplyStatusViewModel;
     query9 = from m in query9
              where m.PrdOrd.Contains("袁")
              select m;
      var count9 = query9.Count();
      ...
    }
 }

 

标签:Code,dbo,void,vReplyStatus,视图,override,public,first
From: https://www.cnblogs.com/daboluo/p/17444258.html

相关文章

  • 定义视图
    select*fromemp;selectempno,ename,job,mgr,salfromemp;效率更高,但复用时输入时比较麻烦  select*fromempjoindeptonemp.deptno=dept.deptno解决方案:定义一个视图(建一个新表(虚拟))createorreplaceviewmyview1     --orreplace:创建或替换,针对以及......
  • leetcode 693. Binary Number with Alternating Bits
    Givenapositiveinteger,checkwhetherithasalternatingbits:namely,iftwoadjacentbitswillalwayshavedifferentvalues.Example1:Input:5Output:TrueExplanation:Thebinaryrepresentationof5is:101Example2:Input:7Output:FalseExplanation......
  • leetcode 637. Average of Levels in Binary Tree
    Givenanon-emptybinarytree,returntheaveragevalueofthenodesoneachlevelintheformofanarray.Example1:Input:3/\920/\157Output:[3,14.5,11]Explanation:Theaveragevalueofnodesonlevel0is3,onlevel......
  • leetcode 496. Next Greater Element I
    Youaregiventwoarrays(withoutduplicates)nums1andnums2wherenums1’selementsaresubsetofnums2.Findallthenextgreaternumbersfornums1'selementsinthecorrespondingplacesofnums2.TheNextGreaterNumberofanumberxinnums1isth......
  • leetcode 463. Island Perimeter
    Youaregivenamapinformofatwo-dimensionalintegergridwhere1representslandand0representswater.Gridcellsareconnectedhorizontally/vertically(notdiagonally).Thegridiscompletelysurroundedbywater,andthereisexactlyoneisland(i......
  • leetcode 682. Baseball Game
    You'renowabaseballgamepointrecorder.Givenalistofstrings,eachstringcanbeoneofthe4followingtypes:Integer(oneround'sscore):Directlyrepresentsthenumberofpointsyougetinthisround."+"(oneround'sscor......
  • leetcode 566. Reshape the Matrix
    InMATLAB,thereisaveryusefulfunctioncalled'reshape',whichcanreshapeamatrixintoanewonewithdifferentsizebutkeepitsoriginaldata.You'regivenamatrixrepresentedbyatwo-dimensionalarray,andtwopositiveintegersr......
  • leetcode 766. Toeplitz Matrix
    AmatrixisToeplitzifeverydiagonalfromtop-lefttobottom-righthasthesameelement.NowgivenanMxNmatrix,return True ifandonlyifthematrixisToeplitz. Example1:Input:matrix=[[1,2,3,4],[5,1,2,3],[9,5,1,2]]Output:TrueExplanation:12......
  • leetcode 575. Distribute Candies
    Givenanintegerarraywithevenlength,wheredifferentnumbersinthisarrayrepresentdifferentkindsofcandies.Eachnumbermeansonecandyofthecorrespondingkind.Youneedtodistributethesecandiesequallyinnumbertobrotherandsister.Retur......
  • leetcode 412. Fizz Buzz
    Writeaprogramthatoutputsthestringrepresentationofnumbersfrom1ton.Butformultiplesofthreeitshouldoutput“Fizz”insteadofthenumberandforthemultiplesoffiveoutput“Buzz”.Fornumberswhicharemultiplesofboththreeandfiveoutp......