ASP.Net Entity Framework - asp.net

I'm just trying the ASP.Net Entity framework its the first time I've tried to use an ORM framework so bear with me If I'm barking up the wrong tree.
To simplify the problem I've got the following 2 tables
Calendar
CalendarID
UserID
Date
EventName
Users
UserId
Username
I've added them both to my Entity Framework model and its established the link between the tables. I'm able to then display a list of Calendars from my MVC view, by using something like
<%= calendarEntry.DateAdded%>
However if I then try to use
><%= calendarEntry.Users.Username%> : <%= calendarEntry.DataAdded%>
It falls over on the call to calendarEntry.Users as it says it is null. Why is the entity framework not pulling through the use details? Do I need to change something in my model designer?
If it helps the code in the MVC controller that sends the data to the view is like this
var Entities = new UnityGamersEntities();
return View(Entities.Calendar);
Really hope that makes sense.

for anyone interested I solved this by using the following code
UnityGamersEntities db2 = new UnityGamersEntities();
ObjectQuery<GameCalendar> gc = db2.GameCalendar.Include("GameTitles");
There seems to be a real lack of tutorials for the entity framework, unless you only ever want to work with single tables I found it really hard to find the information I need.
hopefully this will change in coming months.

Gav,
There is another way you can get Linq to Entities to populate the Users Table.
Every Foreign Key and Collection has a "Load" Method on it which will go off to the database and, in your case, fetch the list of users linked to the current calendar and populate the collection. It's kind of like lazy loading.
If you were to add this line it should work:
<!-- Load up Users unless it's already Loaded -->
<% if(!calendarEntry.Users.IsLoaded) calendarEntry.Users.Load(); %>
<!-- Your Line -->
<%= calendarEntry.Users.Username%> : <%= calendarEntry.DataAdded %>
Hope it helps.
PS - I hear you on the lack of documenation
Crafty

You need to tell the entity framework to load the Users for the Calendar.
You can do this VIA the LINQ query, simply:
Calendar cal = (from c in Calendar
where c.CalendarID.Equals(input)
select new
{
c,
c.Users
}).FirstOrDefault().c;
Which says, load the calendar and all its users.
EDIT: There are probably other ways to load the users, this is just the LINQ way.

Related

Using ASP.NET Resources in React

I have an old MVC 4 project that uses ASP.NET Resources in Razor views for localization.
I.e in a Razor view you may see
Views/Register.cshtml:
#Resource(() => Local.TermsAndConditions
This will go off and fine
Resources/Register.resx
And find the 'TermsAndConditions' parameter with the correct culture.
Now I don't actually know how all of this works, I've never worked on a multi-lingual application before, but I know that these resx files don't even have the correct information - what actually happens is somehow we fetch these from what looks like a complicated set of SQL tables in the database, using a built ResourceCache class.
I am trying to re-write the front-end using React, but am struggling with how to keep the localization - there are hundreds of entries and I am pulling my hair out a little here.
The only solution I can think of, is to manually find all the keys that would be required to lookup at the top of the view, and send these off to a custom API that will process these values for me, but feel like that may cause a large overhead on my application!
Any ideas?
So I solved this by creating a simple API method
List<string, string> LocaliseStrings (List<string> keys)
{
// get UI culture
// look up translated string
// add to return list in KVP
}
This would be called on every front-end page before anything else, and return the strings necessary

Entity Framework problem in new Entity Inheritance

Could someone with some good knowledge answer this question please. Im having a problem with the schema in my Students.aspx page. I have done the walkthrough, but I get an error and I have copied the edmx file from the sample into my application and I still get the error. This is the error:
'EnrollmentDate' is not a member of
type 'SchoolModel.Person' in the
currently loaded schemas. Near simple
identifier, line 6, column 4.
I have also created a new EntityDataSource and I have the same problem. The sample works fine but I can't seem to get the EnrollmentDate and HireDate fields to be part of the 'SchoolModel.Person' Entity. The part which is Upto setting the EntityTypeFilter then I run the app and I get problems
It sounds like you're following the example on MSDN. By the end of the example, the fields EnrollmentDate and HireDate are no longer on the SchoolModel.Person class, they're on the subclasses SchoolModel.Instructor and SchoolModel.Student.
I faced the same problem while going through that walkthrough. The solution: Just delete the old EntityDataSource control on the page, put new EntityDataSource, configure it as given in walkthrough (with entity set name: People; EntityTypeFilter: Student or instructor), And every thing works as it should!!
Faraz
It sounds like you may have missed one or more EDS controls when you added the EntityTypeFilter attributes. Are you sure all your EDS controls that access students or instructors have EntityTypeFilter="Student" or EntityTypeFilter="Instructor"?

asp.net subsonic 2.2 paging linked table collection

I'm creating a small forum for my CMS and I'm using subsonic 2.2 as my DAL.
I'm loading my theads like this:
DAL.ForumThread item = DAL.ForumThread.FetchByID(id);
In my database my ForumPosts table looks like this:
ForumPostID | ThreadID | Description | UserID | CreatedOn| etc
So now when I have my DAL.ForumThread item I can load the connected post collection by using:
item.ForumPosts();
This all works great, but the problem is that I'm using serverside paging and want to add some additional select parameters too like showing only active records.
Is this even possible when using SubSonic 2.2 ? The workaround I have now is just creating a new SubSonic.Query and select the posts by threadid and there I can set pageindex and pagesize without problems but I think this can be done easier?
I also would like to know if it makes any difference performance wise by just using item.ForumPosts() or starting a new query, I think the forumposts are already in the ForumThreads collection and don't require a new database call right?
I hope someone can point me in the right direction!
Thank you for your time and merry christmas.
Kind regards,
Mark
This goes a bit late, but. You can instead of using the Query tool use something like this:
ForumPostsCollection posts = new ForumPostsCollection().Where(ForumPosts.Columns.ThreadId,1).Load();
You can use as many parameters as you want just repeat the where clause like:
ForumPostsCollection posts = new ForumPostsCollection().Where(ForumPosts.Columns.ThreadId,1).Where(ForumPosts.Active,true).Load();
You can even use a comparison in the one of the Where methos overloads.
A for paged results, I am sure you can do it, but I dont have subsonic here with me atm, and i cannt find anything in the docos for version 2.2, there is something for v3 though.
About your second question, Subsonic uses Lazy Loading of collections, meaning that when you execute the method ForumPosts, it issues another database call to fecth that collection. The same is not true for Parent entities, the rule here is if its a method eg: ForumPosts() - A new database call is done, it it is a property eg: post.Thread it will be loaded.

Is it possible to access a profile without updating LastActivityDate?

In asp.net (using MVC, but this happens in regular too)
Profile.GetProfile(username);
will update the LastActivityDate for that user. This is not intended when someone else is viewing that user's profile.
In the membership class you can specify whether to update this date with a second param, like so:
Membership.GetUser(username, false); // doesn't update LastActivityDate
Membership.GetUser(username, true); // updates LastActivityDate
Is there anyway to do something similar in the Profile provider without writing my own provider?
You might use one ugly workaround which includes changing aspnet_Profile_GetProperties stored procedure. This one is responsible for getting the properties while accessing user profile.
Open this procedure and you will find following code at the bottom:
IF (##ROWCOUNT > 0)
BEGIN
UPDATE dbo.aspnet_Users
SET LastActivityDate=#CurrentTimeUtc
WHERE UserId = #UserId
END
Remove it in order to stop updating the LastActivityDate. You will still get LastActivityDate updated when calling Membership.GetUser(username, true);.
You might look at using a provider that someone else has written, rather than write your own.
This one on Scott Guthrie's blog includes stored procedures which could be called directly by your own code to get the information:
http://weblogs.asp.net/scottgu/archive/2006/01/10/435038.aspx
This page has an msi download which installs a sample application for working with custom Profile data. The table based profile performs a lot better than the default on, where all of the profile data is contained in a single database field. The table based one is also a lot easier to query directly, which will help you with your question. The stored procedure from the sample schema is called getCustomProfileData
Otherwise, just query the database directly.

Set service field value in Dynamic Data

In my project many tables are linked to aspnet_Application table by ApplicationId foreign key. I don't want the users to view or edit it, so I'm looking for way to preset this sql table field value before the insert query is executed. I still have scaffolding enabled for this column (in order for DD to generate the right sql script) but I'm hiding this column/field in all my edit/list/insert pages.
Ideally I'm looking for a place to inject my code right before DynamicInsert is executed for any table in my LinqToSql class.
Thanks
So after some digging around I came up with an acceptable solution. I've created a partial class for my data context and added a partial Insert_ method for every table that's linked to the aspnet_Applications. In every method I set the ApplicationId field to current application id.
It looks like this:
public partial class MyDataContext
{
partial void InsertMyTable(MyTable instance)
{
instance.ApplicationId = HttpContext.Current.Session["ApplicationId"] as Guid?;
this.ExecuteDynamicInsert(instance);
}
}
Note that you can't execute other LINQ statements while in this method. In particular I had to store the application id in session rather than querying the aspnet_Applications table.
While this is acceptable solution it isn't perfect (a lot of repetitive code) so if anyone knows better throw me a bone here :)
In the future the best solution would be to use DomainService part of .Net RIA Services preview just released at MIX09 see there videos here:
.NET RIA Services - Building Data-Driven Applications with Microsoft Silverlight and Microsoft ASP.NET
Microsoft ASP.NET 4.0 Data Access: Patterns for Success with Web Forms
The first is an introl to .net RIA Services from the point of view od Silverlight but more of it applied to DD the second is David Ebbo's presentation at MIX and shows how DomainService works with DD I think this is the way forward as you can do all your business logic here in the DomainService.

Resources