How can pass the model property as an argument in a method(如何在方法中将模型属性作为参数传递)
转载作者:bug小助手更新时间:2023-10-24 22:48:39244
I am trying to pass model class property as an argument to the method IsNameDuplicateAsync and use the model class property name from the argument. I am trying to check the Product Description is already in the database. So how can I rewrite the code using the property name as from the argument
What is Set in this case? What is TModel? It looks like you aren't using any models but trying to execute an ORM query with EF Core. The whole point of using ORMs is to give the impression of working with objects, eg db.Customers.AnyAsync(c=>c.Name==somename) not tables, rows, and strings. If you don't want to work that way, it's a lot easier to either write the SQL query or use a micro-ORM like Dapper.
Which EF version are you using? Newer versions make it easier to work with ad-hoc queries. LINQ-to-Entities works with expressions, so you may be able to pass a Expression<Func<TSource,bool>> expression to your method, if it's simple enough. For complex expressions you may have to use LinqKit
x => EF.Property<object>(x, columnName) == "TestName". See docs: EF.Property method.
X=>EF.Property
优秀答案推荐
You can use reflection to access the property by its name passed as an argument. For example:
您可以使用反射通过作为参数传递的名称来访问属性。例如:
if (await IsPropertyDuplicateAsync<Product>("Description", "TestName")) { var tested = "Ok"; }
public async Task<bool> IsPropertyDuplicateAsync<TModel>(string propertyName, string propertyValue) where TModel : class { var propertyInfo = typeof(TModel).GetProperty(propertyName); if (propertyInfo == null) { throw new ArgumentException($"The property '{propertyName}' does not exist in the type '{typeof(TModel).Name}'."); }
There is a disadvantage here that you can make a typo in the property name, which will lead to an error at runtime.
这里有一个缺点,您可能会在属性名称中输入错误,这将在运行时导致错误。
I can suggest another option that gives a stricter typing of the code.
我可以建议另一个选项,提供更严格的代码键入。
public async Task<bool> IsNameDuplicateAsync<TModel>(Expression<Func<TModel, bool>> expr) where TModel : class { return await Set<TModel>().AnyAsync(expr); }
我是一名优秀的程序员,十分优秀!