RemoveDataRecord(int id) - 动态设置TEntity

发布于 2024-12-15 11:07:45 字数 544 浏览 1 评论 0原文

var repo = new MyRepo();
repo.RemoveDataRecord<MyProj.Data.Person>(5);

上面的代码从我的 linq to sql 存储库中的 Person 表中删除了一条记录。

这就是我想做的:

var repo = new MyRepo();
repo.RemoveDataRecord<"MyProj.Data.OrderItem">(17);

目的:每个管理页面都有一个记录表,每个记录都有一个“删除”链接,如下所示:

<a href="#" id="17" type="MyProj.Data.OrderItem">delete</a>

这样我就可以获取要删除的项目的 ID 和类型。

这可能吗?类似于 repo.RemoveDataRecord<"MyProj.Data.OrderItem">(17); ?我想我需要反思。谢谢!

var repo = new MyRepo();
repo.RemoveDataRecord<MyProj.Data.Person>(5);

The above removes a record from the Person table in my linq to sql repository.

This is what I'd like to do:

var repo = new MyRepo();
repo.RemoveDataRecord<"MyProj.Data.OrderItem">(17);

Purpose: each admin page has a table of records, and each record has a "delete" link that looks like this:

<a href="#" id="17" type="MyProj.Data.OrderItem">delete</a>

So I can grab the id and the type of item to delete.

Is this possible? Something like repo.RemoveDataRecord<"MyProj.Data.OrderItem">(17); ? I'm assuming I need reflection. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

忆依然 2024-12-22 11:07:45

您可以尝试这样的操作:

首先,让我们获取实体类型的类型反射:

var targetEntityType = Type.GetType("MyProj.Data.OrderItem");

然后,我们需要通用RemoveDataRecord方法定义的反射

MethodInfo genericMethodDefinition = typeof(MyRepo).GetMethod("RemoveDataRecord");

请参阅此处,如何以可重写的方式执行此操作:是否有与 typeof 等效的 C#属性/方法/成员?

现在,每次必须调用此方法时,您应该:
根据泛型方法定义获取泛型方法的反射:

MethodInfo genericMethod = genericMethodDefinition.MakeGenericMethod(targetEntityType);

并调用它:

genericMethod.Invoke(repo, new object[] { 17 });

You can try something like this:

First, let's get type reflection of your entity type:

var targetEntityType = Type.GetType("MyProj.Data.OrderItem");

Then, we need a reflection of generic RemoveDataRecord method definition

MethodInfo genericMethodDefinition = typeof(MyRepo).GetMethod("RemoveDataRecord");

See here, how to do this in refacrable way: Is there a C# equivalent of typeof for properties/methods/members?

And now, each time you have to call this method, you should:
Get reflection of generic method, based on generic method definition:

MethodInfo genericMethod = genericMethodDefinition.MakeGenericMethod(targetEntityType);

And invoke it:

genericMethod.Invoke(repo, new object[] { 17 });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文