I am fairly new to ASP.NET and I am trying to figure out how to use the entity framework model to data from a textbox field and store it in an existing field in a database which is available to the application .
I looked around on the internet and some solutions were to use a detailView but that would require me to recode the entire page and I would like to avoid that.
Can anyone provide any inputs on how to go about that ?
Thanks !!
For an introduction to using EF with ASP.NET see the tutorials at http://asp.net/entity-framework/tutorials -- there are two series there for Web Forms and one for MVC. Both of them have examples of using textboxes.
var context = new MyEntities();
var myObject = new myObjectType();
myObject.myValue = myTextBox.Text;
context.myObjectTypes.Add(myObject);
context.SaveChanges();
Related
I'm fairly new to asp.net mvc, so please bear with me.
I want to implement a calendar functionality, and all the tutorials I've looked at use database-first approach and have the edmx file (Entity Data Model)
I'm using code first and what can I do regarding the code that references this edmx file? do I reference context instead?
example:
public JsonResult GetEvents()
{
//Here MyDatabaseEntities is our entity datacontext (see Step 4)
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
var v = dc.Events.OrderBy(a => a.StartAt).ToList();
return new JsonResult { Data = v, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
Sorry if this question is vague or not clear.
Thank you and I'd appreciate help!
In code first, you don't need an edmx file, because everything is in your own code. The basic building blocks are:
A class that inherits from DbContext. This will be equivalent to the MyDatabaseEntities class in your sample.
A set of entity classes. They basically just need to be plain classes with auto properties corresponding to your database columns. For built in conventions to work, you also need an ID, for instance an int property named Id
A set of properties on your DbContext class of type DbSet for every type T which is an entity you would like to query against. This is the Events property in your example.
In more advanced scenarios you customize the mappings beyond what the conventions can infer automatically. This can be done with attributes on your entity classes, or via a special set of APIs that can be called on your context at startup
Go to Sql server inside your database there is a folder Database Diagram, Right click New Database Diagram and explore it.
I have experience with webForms and now i am starting to learn MVC, oh boy....everything looks so different. Since my background is webForms, I just want to make sure If am doing this properly. I am pulling data (Queries, Stored Procedures etc) from MS SQL Server & Goal is to represent them within view. here is what I have done so sar.
Here is my Model
Class Product ' Just a Template
private _title
private _price
' property implementation etc
End Class
Class ProductModel ' Returns Actual Data
Function getProducts as list(of product)
' use SqlDataReader to Execute the Stored Procedure
' Populate a list(of product)
' list.add(new product(title,price))
' Return the List
end function
Function getTopProducts() as list(of products)
End Function
End Class
Now Here is my ProductsController index() ActionMethod.
Dim p as new ProductModel
return view(p)
Then within my View (Which is strongly typed for ProductModel Class), I am using a For each on Model.getProducts or Model.getTopProducts and showing the data on screen.
Now Few questions...first of all, is my approach reasonable? is it a standard way of setting up Models with MVC? If not then please correct me.
Secondly, all the examples I see online, i see people using LINQ, EF etc....however in my environment performance is very important, and i am almost always returning data using Stored procedures, so is it OK to use pure ADO.NET or using LINQ/EF can help me out in some way?
...is my approach reasonable? is it a standard way of setting up
Models with MVC? If not then please correct me.
Yes, it's best practice to use a viewmodel than work with your entities directly on your views.
is it OK to use pure ADO.NET or using LINQ/EF can help me out in some
way?
It's perfectly fine to use pure ADO.NET if you feel doing all the dirty works an ORM provides.
You approach is the one that is mostly shown when you learn about MVC. However, if you want to be a bit picky about naming convention then your ProductModel would be called ProductViewModel. This ViewModel will allow you to pass more information to View than it is available in your Product class (which is your model class). But this is insignificant although you should get used to using View with ViewModels.
As for your second question you can use anything you want as data access technology. Entity Framework is promoted by Microsoft as one of its technologies for manipulating with the information in a database. However, if you want you can use ADO.NET with stored procedures, or you can use RavenDB with its own client interface. It's really up to you.
Mates, I want to update a role description using my application
I donĀ“t know what is the better way to connect to the database and run a UPDATE statement.
Would it be Entity Framework? LINQ? None of this 2 options..
Please, suggestions.
I would say that Entity Framework would be currently the best solution for you. Not only it is strongly supported by Microsoft (well Silverlight was as well) but:
If you start with it, you can use designer. It's graphical UI will guide you when generating the model (based on database) or generating the database schema when starting with model.
Read some tutorials abut it:
http://msdn.microsoft.com/en-us/data/ee712907
And later take a look how to use some more profesionla techniques as Repository pattern or unit of work
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application
Not Linq ..well yes linq, but linq is the querying framework where as entity framework is the object relational mapper. So Both actually. You could do this in various other ways but those two technologies work very well together from my experience.
In Visual studio you would create a new ADO.NET project template which you then hook up to your database. and then you can update the tables and do a whole bunch of stuff. Linq is build into .NET so technically you can query any objects using linq ( which makes it so much fun ) and because your entity is an object you just reference it ( first declare it ) and then play with it
FooModel foo = new FooModel(); // Entity
var fooQuery = from _ in foo.DescriptionTable // Linq query
where _.Description == SelectedDesc // table selection query
select _;
foo.Add(fooQuery); // add to database
foo.SaveChanges(); // save changes
Something like that. There is a bit more to it that would project specific but you would have to give more details.
It is most certainly worth learning both technologies and have doubt you will find them very useful. Both can get very complex but for what you need it for you just need the basics down and then you can explore from there.
OK, I think I'm getting mad here...
I thought this should be super simple, but I just can't figure out how to do that.
This is what I'm trying to do:
I want to create an rdlc report using the ReportViewer control in ASP.NET 4 (VS 2010), and, as its datasource, use a class with some properties.
I tried everything I can think of, but I just can't figure this out. All the docs I found state that the object should appear in the DataSource pane of the website, but I can't make it appear there.
I would like the fields of the class to appear in the report desiger so I can use them - but I can't do that either.
Using the designer, I can only define new dataset - I don't want to use dataset, but business objects!
So - how can I do that? Do I have to use some kind of DataSource control? How can I make the report designer know about the business object?
Thanks!
Memi
did you follow this tutorial?
everything you must do is:
define your DTO classes or generate it using EF4 (for example)
define your business classes with some methods (like GetAll...)
build your solution (that's important)
now from your report designer you can choose methods from business classes as dataset and drag and drop field from the DTO classes
when you choose that report to display in the reportviewer, the datasource object will be added for you
I found this blog very helpful.
When you create a new datasource for your rdlc, in the Dataset Properties dialog:
1) In the Data source drop down, select the namespace that contains the class which contains the public method (see #2).
2) In the Available datasets drop down, select the public method that returns an IQueryable of your business objects.
Is your business object class marked as public? I've seen in a video that it must be public.
I have the same problem and found a way around it. For some reason if you develop a ASP.NET application Microsoft took away add new datasource functionality. The way around is not great but it does work. I use all objects and I use the Enterprise library and I want to use my objects for my reports it only makes sense why they don't enable you to do this. I have no idea why Microsoft would not allow this functionality for web apps.
But that leaves windows apps it works so what I did was create a separate windows project include my objects that I want to bind to in that project and create the report on the forms project. I then bring that report into my Asp.net web app and call it through code. Here is a few pieces of code that I use to do this. This is in VB but could be converted to C#. I also have a drop down list that selects the report that is needed and a case statement that gets the data.
Private Sub LoadReport()
Try
pnlReport.Visible = True
Dim Dal As New DataAccess
Dim objRptOutputData = New Model.RptClientCollection
Dim lr As LocalReport = OutputReportViewer.LocalReport
Dim rds As New ReportDataSource
lr.DataSources.Clear()
OutputReportViewer.Visible = True
OutputReportViewer.ProcessingMode = ProcessingMode.Local
OutputReportViewer.LocalReport.EnableHyperlinks = True
Dim SelectedReport As Integer = 0
If Me.ddlReport.SelectedItem.Value IsNot "" Then
SelectedReport = Me.ddlReport.SelectedItem.Value
End If
Select Case SelectedReport
Case ConstantEnum.Reports.ActiveWaitingList
objRptOutputData = Dal.GetRptClientsByStatus(ConstantEnum.Status.ActiveWaitingList)
lr.ReportPath = "Reporting\Report1.rdlc"
rds.Name = "dsClient"
rds.Value = objRptOutputData
Me.lblCount.Text = "Count: " & objRptOutputData.Count
Case ConstantEnum.Reports.InactiveWaitingList
' This is a small app I have about 15 case statements if it was bigger I would of done this selection a bit different.
End Select
lr.DataSources.Add(rds)
lr.Refresh()
OutputReportViewer.DataBind()
Catch ex As Exception
ExceptionUtility.SendError(ex, "Reports", "LoadReport")
End Try
End Sub
Have you seen this earlier version? Is this what you need:
http://msdn.microsoft.com/en-us/library/ms252073(v=VS.80).aspx
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.