简体   繁体   English

如何将参数传递给实体框架 Model?

[英]How to pass a parameter to the Entity Framework Model?

I want to save UserID of the creator for every record in the database (I have a field for it in every table), I found that I can do that by overriding SaveChanges method.我想为数据库中的每条记录保存创建者的UserID (我在每个表中都有一个字段),我发现我可以通过覆盖SaveChanges方法来做到这一点。

The only problem is that UserID is stored in a session variable in the web project and the EF exists in a separated project library.唯一的问题是UserID存储在 web 项目中的 session 变量中,并且 EF 存在于单独的项目库中。 And no access from the dll to the application.并且无法从 dll 访问应用程序。

What's the best approuch for my case?我的情况最好的方法是什么? Is it by passing the UserID by creating a new override for SaveChanges with UserID parameter?是通过使用 UserID 参数为 SaveChanges 创建一个新的覆盖来传递 UserID 吗? or any other idea?或任何其他想法?

I myself am a beginner so sorry if you dont like the answer:-)我本人是初学者,如果您不喜欢答案,我很抱歉:-)

From what i understand you are passing the values to be added to the db by using the CONTEXT.TABLENAME.ADD method.据我了解,您正在使用 CONTEXT.TABLENAME.ADD 方法将要添加到数据库的值传递给数据库。

You say u have field for userid in every table, then its simple just get user id from the session variable and pass it as you are passing the remaining data.您说您在每个表中都有用户 ID 字段,那么它很简单,只需从 session 变量中获取用户 ID 并在传递剩余数据时传递它。

It will help if you provide more information.如果您提供更多信息,将会有所帮助。

Passing it is definitely the best approach as you'll find yourself getting tied in knots if you try to tightly bind your Web Context to your data context in seperate libraries.传递它绝对是最好的方法,因为如果您尝试将 Web 上下文与单独库中的数据上下文紧密绑定,您会发现自己陷入困境。 It's also not a great "seperation of concerns" so if you ever use your data library for anything other than your website, it won't work.这也不是一个很好的“关注点分离”,因此如果您将数据库用于您的网站以外的任何其他内容,它将无法正常工作。

If you need to/insist on accessing session outside of the main project you can do it with:如果您需要/坚持在主项目之外访问 session ,您可以这样做:

HttpContext.Current...

and adding a reference to System.Web.并添加对 System.Web 的引用。 Not really best practice in this case, but it's possible.在这种情况下并不是真正的最佳实践,但它是可能的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM