【问题标题】:How can i add var item in EF?如何在 EF 中添加 var 项?
【发布时间】:2017-05-09 13:10:50
【问题描述】:

我有一个长度未指定的数组。也许 100 , 110 , ...

对于我拥有的每个值:

  int a1 = array[0];
    var r1 = from row in db.products
    where row.id == a1
    select row;
    int a2 = array[1];
    var r2 = from row in db.products
    where row.id == a2
    select row;
...

我怎样才能得到 (r1 + r2 + r3 + ... (= sum)) 的总和?

总结之后,我想序列化:

string s1 = js.Serialize(sum);

【问题讨论】:

  • 在下面的答案中,对于序列化,您可以使用 JSON NewtonSoft。 var s1 = Json(new { Summation = summation }, @"application/json"); var jsonResult = s1.Data.ToString();

标签: c# entity-framework-4


【解决方案1】:

您可以在代码中执行此操作:

表:

--use your db
USE [Breaz]
GO
/****** Object:  Table [dbo].[theProducts]    Script Date: 5/8/2017 3:49:33 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[theProducts](
    [theId] [int] IDENTITY(1,1) NOT NULL,
    [id] [int] NULL,
 CONSTRAINT [PK_theProducts] PRIMARY KEY CLUSTERED 
(
    [theId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
SET IDENTITY_INSERT [dbo].[theProducts] ON 

GO
INSERT [dbo].[theProducts] ([theId], [id]) VALUES (1, 5)
GO
INSERT [dbo].[theProducts] ([theId], [id]) VALUES (2, 6)
GO
INSERT [dbo].[theProducts] ([theId], [id]) VALUES (3, 7)
GO
SET IDENTITY_INSERT [dbo].[theProducts] OFF
GO

程序:

//use your database dbcontext
       using (BreazEntities21 db = new BreazEntities21())
        {
            int[] a1 = { 5, 6 };
            var r1 = (from row in db.theProducts
                     where a1.Contains((int)row.id)
                     select row).ToList();
            int[] a2 = { 7 };
            var r2 = (from row in db.theProducts
                     where a2.Contains((int)row.id)
                     select row).ToList();
            var mergedList = r1.Union(r2).ToList();
            var summation = mergedList.Sum(r => r.id);
            var s1 = new JavaScriptSerializer().Serialize(summation);
        }

【讨论】:

    猜你喜欢
    • 2015-07-08
    • 2014-11-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多