Does Entity Framework need a Session HttpContext on CRUD? - session

I've watched some class about Entity Framework with MySql and Sql Server.
First the teacher uses the Entity from a database, where he creates the context DB and than he start the insert
using(sampleEntities ctx = new sampleEntities()){
client clt = new client();
clt.name = txtName.Text;
clt.phone = txtPhone.Text;
ctx.Add(clt);
ctx.SaveChanges();
But other teacher does something different with DAL, BLL and UI usgin session and httpContext, he says Entity needs this Session to avoid "persistence conflict" since the first example is using the same "connection/session" for lots of users, so that is what he does:
public static sample01Entities Current
{
get
{
if (System.Web.HttpContext.Current.Session["SampleDbContext"] == null)
{
db = new sample01Entities();
System.Web.HttpContext.Current.Session["SampleDbContext"] = db;
}
return db;
}
}
`
and then in Dalcity
public void Add(cidade c)
{
SampleDbContext.Current.cidade.Add(c);
SampleDbContext.Current.SaveChanges();
SampleDbContext.Current.ChangeTracker.Entries<cidade>();
}
The question is: is it safe to use the first example without jeopardize a website? Or should I use the session all the time for all the CRUD methods?
Thanks

Storing the context in the session is a terrible idea.
Read the following answer about it:
Entity Framework Object Context in ASP.NET Session object?
The context should be either created by method or by request.
To answer to your question:
Yes it safe to use the first approach and for sure more recommended then storing the context in a session.

Related

Use Oracle's DBMS_SESSION.set_context in Entity Framework Core

I have the need to show on my .net core program an Oracle view that in the database has some columns filtered by
... WHERE dictionary.LANGUAGE = SYS_CONTEXT ('CLIENTCONTEXT', 'LANGUAGE');
Obviously fetching the data directly on the application makes those columns return a null value.
I would need to implement something like this
OracleCommand cmd = new OracleCommand(String.Format("BEGIN DBMS_SESSION.SET_CONTEXT('CLIENTCONTEXT', 'LANGUAGE', '{0}'); END;", ActualLanguage), ORACLEconn as OracleConnection);
cmd.ExecuteNonQuery();
How would I go about implementing the code using Entity Framework Core? Would I need to call it once on the model creation or every time I create a new DbContext?
Thank you.
If you have a DbContext constructor that's only used when you want the session context set, you can force the connection open, and it will remain open until your DbContext is disposed. eg
public Db(DbContextOptions opts) : base(opts)
{
this.Database.OpenConnection();
this.Database.ExecuteSqlRaw("BEGIN DBMS_SESSION.SET_CONTEXT('CLIENTCONTEXT', 'LANGUAGE', 'whatever'); END;");
}
Or you can use an Interceptor to run the command every time a connection is opened.

Spring #Transactional is not commited. Neo4J

I have an entity User that has relationship WORKS_FOR with an entity Organization. Organization has relationship HAS_EMPLOYEE with all users that are in and a relationship HAS_ANCHOR, with one anchor for the whole organization to manage it. I am trying to update organization entity with another user from "HAS_EMPLOYEE" list to become a new anchor. But there are no changes in db after the method and no runtime exceptions are thrown.
#Transactional
public OrganizationDTO changeAnchorForOrganization(UUID prevAnchorId, UUID newAnchorId) {
User newAnchor = userService.getAnyUserById(newAnchorId);
if (!newAnchor.isActive()) {
throw new BadRequestException(ExceptionType.REQUEST_BODY_INVALID);
}
User prevAnchor = userService.getAnyUserById(prevAnchorId);
Organization organization = getOrganizationByAnchorId(prevAnchorId);
Set<String> prevAnchorPermissions = prevAnchor.getPermissions();
prevAnchorPermissions.remove(SubRolesConstants.anchor);
prevAnchor.setPermissions(prevAnchorPermissions);
Set<String> newAnchorPermissions = newAnchor.getPermissions();
newAnchorPermissions.add(SubRolesConstants.anchor);
newAnchor.setPermissions(newAnchorPermissions);
organization.setAnchor(newAnchor);
return organizationMapper.entityToDTO(organization);
}
organization.setAnchor(newAnchor); this line is not working?
The result DTO has the changes made to org anchor but db is not. And if i'll try to get the ogranization after this method i'll get the old version of organization(with previous anchor)
Stuck with that for a long time. Maybe somebody can help me?
I was missing organizationRepository.save(organization).I think it's because of neo4j because by default #Transactional annotation commit any changes made to entities at the end of the service call. Or it's just a bug.

How to Persist data using session variable in mvc3 razor view?

I am working in MVC3 Application with Razor. In my Account controller after validating the user, i am getting the user ClientID from Database. Here i want to persist ClientID in Session variable. which was using across the all controller and Razor view.
I have no idea as to what is the best way to implement this.OR How to persist data in the session variable. And how to use persisted data in the session variable in across the controller.
Thanks for your help..
I usually write a Session wrapper that allows me easy access to it in the future:
public class SessionData
{
const string ClientId_KEY = "ClientId";
public static int ClientId
{
get { return HttpContext.Current.Session[ClientId_KEY] != null ? (int)HttpContext.Current.Session[ClientId_KEY] : 0; }
set { HttpContext.Current.Session[ClientId_KEY] = value; }
}
}
After that you can access it from anywhere like this:
int clientId = SessionData.ClientId;
If you want you can use whole objects in Session like this.
Or you can set it like so: SessionData.ClientId = clientId;
If you are using ASP.NET Forms Authentication, the user name is already stored in a cookie. You can access it from the Controller via
Controller.User.Identity.Name
It's possible to store the user ID as the user name. When you call something like
FormsAuthentication.RedirectFromLoginPage
Give it the ID instead of a name. The ID can then be found using the method above and no extra session data is necessary. If you want to store something in the session, just call
Session["UserID"] = value;
From your controller.

Receive data in MVC controller from webrole

I understood how to communicate between Web, Worker role and the flow in MVC architecture.
My question is, after I query the data from a table in web role, how can the controller in MVC get this data to diplay in the view?
I tried using a global static variable in webrole, where the data gets populated, but when I access the static variable from the controller, it only returned 'null'. Why am I getting a null?
Thanks.
ok, in case you use the storage client, the implementation would be like:
Create your Model:
public class MyEntity : Microsoft.WindowsAzure.StorageClient.TableServiceEntity
{
public MyEntity()
{
PartitionKey = DateTime.UtcNow.ToString("MMddyyyy");
RowKey = string.Format("{0:10}_{1}",
DateTime.MaxValue.Ticks - DateTime.Now.Ticks, Guid.NewGuid());
}
// Define the properties.
public string Title { get; set; }
public string Name { get; set; }
}
}
2. Define your context class:
public class MyDataContext : TableServiceContext
{
public MyDataContext(string baseAddress,
StorageCredentials credentials)
: base(baseAddress, credentials)
{ }
public IQueryable GetMyEntity
{
get
{
return this.CreateQuery("MyTableName");
}
}
}
Implement your controller action method:
public ActionResult Index()
{
var context = new MyDataContext(storageAccount.TableEndpoint.AbsoluteUri, storageAccount.Credentials);
var results = from g in context.GetMyEntity
where g.PartitionKey ==
DateTime.UtcNow.ToString("MMddyyyy")
select g;
return View(results.FirstOrDefault());
}
this is reference code only, which is very ugly and will hardly work as it is, but it still provides an example of how you can query the table storage in your MVC project.
are we talking about an application whose MVC part is hosted in a worker role and which gets data from a web role which is querying the table storage? Or are we talking about a ASP.NET MVC application here which is hosted in a web role?
static variables is not a good idea at all because of concurrency issues.
in case of scenario 1, how do you communicate with a web role? via web service call directly?
you cold simply call the service from your controller or delegate the call to another layer and then put this data in your model which is then displayed by the corresponding view.
have you tried debugging this application locally using the [azure local dev env][1]
[1]: http://blogs.msdn.com/b/morebits/archive/2010/12/01/using-windows-azure-development-environment-essentials.aspx ? or do you use the real azure infrastructure? Are you sure you are getting the data from your query? maybe the query is wrong? have you observed any exceptions?
we need more information here to be able to help you

Consuming Service Operations of an ADO.NET Data Service from a .NET Client

I am trying to build an ADO.NET Data Service with lots of entities and a few service operations. On one side I created a ASP.NET Web Application, in which an ADO.NET Entity Data Model and an ADO.NET Data Service are located. On the other side I created a second ASP.NET Web Application that has a Service Reference to the Data Service.
Entities are coming through very well, I can use LINQ to retrieve the data I want:
TestEntities entities = new TestEntities(
new Uri("http://localhost/service/service.svc"));
var query = from customer in entities.Customers
where customer.ID == 1234
select customer;
query.ToList();
This works. However, retrieving information through Service Operations completely eludes me.
Data Service-side code:
public static void InitializeService(IDataServiceConfiguration config) {
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
}
[WebInvoke]
public IQueryable<Customer> GetSomeCustomers() {
TestEntities entities = new TestEntities();
return from customer in entities.Customers
where customer.ID > 0 && customer.ID < 20
select customer;
}
When I added the Service reference to my client project, Visual Studio didn't pick up on any Service Operations. I know I can access them through constructed URIs and the BeginExecute method of either the DataServiceContext object or the TestEntities object (in this case), or something like that, but that is not how I want it.
What I want is to use LINQ to go through the returned data of the Service Operation.
Is this possible? It should be, right?
Simple stuff once you know.
Just a few things to know:
Currently DataServiceClientGenerator (which uses the EntityClassGenerator) doesnt create methods for the service operations.
Using CreateQuery method on the context is not supported for service operations, currently they work because there is no validation on the client side for that (you will notice that if you use CreateQuery the "()" is added to the end of the Query Method like this "http://localhost/service.svc/method()?parameter=2", you can use CreateQuery but it is not recommended.
Not all Service operations return values, but for this example i will only show an example for the ones that do.
public partial class NorthwindEntities
{
public IQueryable<Order> OrdersByRegion(int regionId)
{
return this.Execute<Orders>(new Uri(string.Format("{0}OrdersByCountry?regionId={1}", this.BaseUri, regionId), UriKind.RelativeOrAbsolute));
}
}
If you require more information please feel free to ask any questions.
PS.: On your example you dont need to create a new data context on your service operation (server side) the DataService has already a reference instantiated when the service is called.
You can actually override the create of the data context on the service side like this:
protected override NorthwindEntities CreateDataSource()
{
return new NorthwindEntities();
}

Resources