简体   繁体   中英

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.

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. And no access from the dll to the application.

What's the best approuch for my case? Is it by passing the UserID by creating a new override for SaveChanges with UserID parameter? 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.

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.

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. 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:

HttpContext.Current...

and adding a reference to System.Web. Not really best practice in this case, but it's possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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