Replies: 1 comment 2 replies
-
Hi @kkulick, You can use Linq from script code, but there are caveats. Let's go through a simple example with First, the basics: public class Product {
public int ProductId { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
public class ProductContext : DbContext {
public DbSet<Product> Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) {
optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=ProductDb;Trusted_Connection=True;");
}
} Now, let's set up the database and script engine: using var context = new ProductContext();
context.Database.EnsureDeleted();
context.Database.EnsureCreated();
var products = context.Products;
products.Add(new Product { Name = "Laptop", Price = 999.99M });
products.Add(new Product { Name = "Desktop", Price = 1499.99M });
products.Add(new Product { Name = "Server", Price = 2999.99M });
context.SaveChanges();
using var engine = new V8ScriptEngine();
engine.AddHostType(typeof(Console));
engine.AddHostType(typeof(Enumerable));
engine.Script.products = products; At this point, all engine.AddHostType(typeof(Func<,>));
engine.AddHostType(typeof(Product));
engine.AddHostType(typeof(Boolean));
engine.Execute(@"
for (let product of products.Where(new Func(Product, Boolean, p => p.Price < 1000))) {
Console.WriteLine(`ID: ${product.ProductId}, Name: ${product.Name}, Price: ${product.Price}`);
}
"); However, you can simplify things by providing a script-friendly version of public static class ScriptHelpers {
public static IEnumerable<T> where<T>(this IEnumerable<T> source, dynamic predicate) {
return source.Where(item => predicate(item));
}
} And now you can do this: engine.AddHostType(typeof(ScriptHelpers));
engine.Execute(@"
for (let product of products.where(p => p.Price < 1000)) {
Console.WriteLine(`ID: ${product.ProductId}, Name: ${product.Name}, Price: ${product.Price}`);
}
"); Good luck! |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
How do I enable linq querying of entity framework DbSet?
I'm trying to use ClearScriptV8 to allow custom scripts to be created which will be executed via ClearScriptV8 in an ASP .Net Core Web API with Entity Framework. I was able to register the database context and can access it in the script however, if I try to write a linq query or use the .Where() or .Select(), it just tells me 'Where' and 'Select' are not found on object 'xyz' where xyz is the entity model. Is this sort of thing supported in ClearTextV8?
Beta Was this translation helpful? Give feedback.
All reactions