Full source code is at the bottom, but here is the highlight.
//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)))
Is there any way to avoid the repeated code of x.ArticleId == demo.ArticleId && x.Title == demo.Title
and reuse one source?
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; }
}
}