在LINQ中的Select语句中执行一些操作

时间:2016-02-17 15:09:06

标签: c# .net entity-framework asp.net-web-api asp.net-web-api2

我有一个Controller动作方法,它返回 IQueryable<AnswerDTO > ,其中有一个名为&#34; Sequence&#34;的字段。我想在一些计算后设置这个字段。我的方法是

<

如何在select语句中设置这样的Sequence属性?

var answer = from dfi in _db.DiaryFormInstances
 //Some Query with LINQ
 select new AnswerDTO()
 {
     Value = dfit.Value,
     //How to perform this operation?
     Sequence = Convert.ToInt32(fti.ItemName.Substring(fti.ItemName.LastIndexOf("_")+1)),
     LastModifiedDate = dfit.LastModifiedDate.Value,
     LastModifiedByID = dfit.LastModifiedByID.Value
 };

如果我在动作方法中执行查询,那么我可以轻松执行此操作。但我想返回IQueryable,我不想在我的action方法中执行查询。

我希望web api执行查询,执行后会正确设置Sequence属性。

1 个答案:

答案 0 :(得分:1)

在调查Linq to Entities中可用的功能后,似乎无法以您希望的方式提取数字。

最好的办法是在数据库中创建一个可以调用的自定义函数。为此,首先在数据库中创建以下函数(例如,您可以使用SSMS直接创建它):

flushedStuff = ''
while not child.expect(r'.+', timeout=5):
    flushedStuff += child.match.group(0)

接下来,您需要在NuGet上添加https://codefirstfunctions.codeplex.com/个套餐,只需搜索CREATE FUNCTION ExtractSequence ( @sequenceString NVARCHAR(50) ) RETURNS INT AS BEGIN RETURN CAST(RIGHT(@sequenceString, CHARINDEX('_', REVERSE('_' + @sequenceString)) - 1) AS INT) END GO

在您添加上述软件包后,您需要将CodeFirstStoreFunctions添加到上下文类的modelBuilder.Conventions.Add(new FunctionsConvention("dbo", this.GetType()));方法中,例如

OnModelCreating

接下来,您还需要将以下内容添加到上下文类中:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Add(new FunctionsConvention("dbo", this.GetType()));
}

最后,您可以在Linq to Entity表达式中使用新功能,因此您可以将选择更改为:

// First parameter should always be CodeFirstDatabaseSchema, this is just a convention used by the store functions package
// The second parameter should match the name of the function in the DB. You can call the method something else but I'd keep it the same as the function name too
[DbFunction("CodeFirstDatabaseSchema", "ExtractSequence")]
public static int ExtractSequence(string sequenceString)
{
    // No need to provide an implementation as this is like a placeholder for the DB function you created in the DB in the first step
    throw new NotSupportedException();
}
相关问题