内联比较工作,但如果我将其包装在一个方法中,LINQ表达式不能被翻译



完整的源代码在底部,但这里是重点。

//Works
if (mydb.Articles.Any(x => (x.ArticleId == demo.ArticleId && x.Title == demo.Title)))
public bool IsSame(WebArticle other)
{
return (ArticleId   == other.ArticleId && Title == other.Title);
}
//Doesn't work
if (mydb.Articles.Any(x => x.IsSame(demo)))

是否有办法避免x.ArticleId == demo.ArticleId && x.Title == demo.Title的重复代码和重用一个源代码?

Program.cs

using Microsoft.EntityFrameworkCore.Storage;
using System.Diagnostics;
namespace EntityTest
{
internal class Program
{
static void Main(string[] args)
{
var mydb = new MyDbContext();
var article1 = new Article()
{
ArticleId = 1234,
Title = "First",
};
var article2 = new Article()
{
ArticleId = 5678,
Title = "Second",
};
var article3 = new Article()
{
ArticleId = 9012,
Title = "Third",
};

mydb.Articles.AddRange(article1, article2, article3);
mydb.SaveChanges();
var demo = new WebArticle()
{
ArticleId = 5678,
Title = "Second",
};
//use inline code
if (mydb.Articles.Any(x => (x.ArticleId == demo.ArticleId && x.Title == demo.Title)))
{
Console.WriteLine("Exists");
}
else
{
Console.WriteLine("Doesn't exist");
}
//use method
if (mydb.Articles.Any(x => x.IsSame(demo)))
{
Console.WriteLine("Exists");
}
else
{
Console.WriteLine("Doesn't exist");
}
}
}
class WebArticle
{
public int ArticleId { get; set; }
public string Title { get; set; }
}
}

MyDbContext.cs

using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EntityTest
{
internal class MyDbContext:DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseInMemoryDatabase("memory");
base.OnConfiguring(optionsBuilder);
}
public DbSet<Article> Articles { get; set; }
public DbSet<ArticleImage> ArticleImages { get; set; }
}
class Article
{
[Key]
public int Id { get; set; }
public int ArticleId { get; set; }
public string Title { get; set; }       
public bool IsSame(WebArticle other)
{
return (ArticleId   == other.ArticleId && Title == other.Title);
}
}
class ArticleImage
{
public int Id { get; set; }
public int ArticleId { get; set; }
public string Url { get; set; }
}
}

将代码更改如下。它可以不使用第三方库。

Program.cs

//use method
//if (mydb.Articles.AsExpandable().Any(x => x.IsSame(demo)))
if (mydb.Articles.Any(Article.IsSame(demo)))
{
Console.WriteLine("Exists");
}
else
{
Console.WriteLine("Doesn't exist");
}

MyDbContext.cs

class Article
{
[Key]
public int Id { get; set; }
public int ArticleId { get; set; }
public string Title { get; set; }
//public bool IsSame(WebArticle other)
//{
//  return (ArticleId   == other.ArticleId) && (Title == other.Title);
//}
public static Expression<Func<Article, bool>> IsSame(WebArticle other)
{
return current => (current.ArticleId == other.ArticleId) && (current.Title == other.Title);
}

最新更新