how to manually insert primary key while inserting a row - EF - asp.net-mvc

I am using MVC 4 with Visual studio 2012. I want to insert primary key while creating row. My tables as as :
<Table("StudentRec")> _
Public Class StudentRec
<Key()> _
Public Property ErNo as Integer
Public Property Name as String
Public Property Branch as String
Public Property Course as String
End Class
<Table("Attendance")> _
Public Class Attendance
<Key()> _
Public Property ErNo as Integer
Public Property Present as Integer
Public Property Leaves as Integer
End Class
My Action Controller is :
<HttpPost()> _
<AllowAnonymous()> _
<ValidateAntiForgeryToken()> _
Function CreateUser(ByVal Modl As StudentRec) As ActionResult
Try
Using dbb As New UsersContext
Dim Erno As Integer = dbb.StudentRec_.Add(Modl).ErNo
dbb.SaveChanges()
Dim Attnd As New Attendance
Attnd.ErNo = Erno ' Not Working, Erno is automatically Set '
Attnd.Leaves = 0
Attnd.Present = 0
dbb.Attendance_.Add(Attnd)
dbb.SaveChanges()
End Using
RedirectToAction("Index", "Home")
Catch ex As Exception
TempData("Errs") = ex.Message
Return View(Modl)
End Try
Return View(Modl)
End Function
How to Manually Set Primary key to table Attendance, with respect to Primary Key of table StudentRec ?

Related

how to combine a viewmodel with various other fields

In my mvc4 application I need to create a view where customers can choose from a list of services, subscribe (by selecting the yes/no option) and give details of the last service date they had the service done and also provide a proposed date for the future service. It should roughly look like as below
.
I have a services table in the database like Services(Id,Name etc) but don't know how shall I combine the other values which I m showing like yes/no and the two dates in a single viewModel and pass it to view and retrieve all the values on post back. In simple words which fields will my viewmodel have? Any ideas. thanks
It sounds like you're asking for more than just a view model. To expand on shenku's answer, this would be my rough/untested approach in VB. It's no way all-inclusive, but hopefully gives you an idea on how to manipulate data, pass it to a view, and get data back on post-back.
Model/DB objects:
Public Class Service
Public Property ServiceID As Integer
Public Property Name As String
End Class
Public Class CustomerService
Public Property CustomerID As Integer
Public Property ServiceID As Integer
Public Property Selected As Boolean
Public Property LastDate As DateTime
Public Property ProposedDate As DateTime
End Class
ViewModel:
Public Class ViewRow
Public Property ServiceID As Integer
Public Property Name As String
Public Property YesSelected As Boolean
Public Property NoSelected As Boolean
Public Property LastDate As String
Public Property ProposedDate As String
End Class
Public Class ViewModel
Public Property TableHeaders As String() = {"Services","Yes","No","Date of Last Service", "Proposed Date"}
Public Property ServiceDetails As List(Of ViewRow)
End Class
Controller:
Public Class HomeController
Inherits System.Web.Mvc.Controller
' Simulating EntityFramework
Protected db As New MyEntities
Function ServiceList() As ActionResult
Dim thisCustomerID As Integer
' *Set user's customer ID*
' Using a LINQ join to combine with other service information
Dim vm As New ViewModel With {
.ServiceDetails = ( _
From custService In db.CustomerService().ToList()
Join service In db.Service().ToList()
On custService.ServiceID Equals service.ServiceID
Where custService.CustomerID.Equals(thisCustomerID)
Select New ViewRow With {
.ServiceID = service.ServiceID,
.Name = service.Name,
.YesSelected = custService.Selected,
.NoSelected = Not custService.Selected,
.LastDate = custService.LastDate.ToString("MMM yyyy"),
.ProposedDate = custService.ProposedDate.ToString("MMM yyyy")
}).ToList()
}
' Passing to a strongly-typed view of type "ViewModel"
Return View("serviceList",model:=vm)
End Function
' This is where you post back, and data can be bound to type "ViewModel"
<HttpPost()> _
Function ServiceList(data As ViewModel) As ActionResult
' *Model Validation / Insert / Update*
' Refresh the page (if you want)
RedirectToAction("ServiceList","Home")
End Function
End Class
Razor View (serviceList.vbhtml):
#ModelType ViewModel
<div>
<table>
<tr>
#For Each head In Model.TableHeaders
#<th>#(head)</th>
Next
</tr>
#For Each detail In Model.ServiceDetails
#<tr id=#(detail.ServiceID)>
<td>#(detail.Name)</td>
<td>#(If(detail.YesSelected,"X",""))</td>
<td>#(If(detail.NoSelected,"X",""))</td>
<td>#(detail.LastDate)</td>
<td>#(detail.ProposedDate)</td>
</tr>
Next
</table>
</div>
To post-back, you'll have to have javascript grab data entered into any input fields (I didn't include any here), and construct a JSON object--with the appropriate data--that reflects the argument in the Controller's post action. I provided an example with an argument of type ViewModel. This means your JSON fields have to match those defined in the ViewModel model, and their values have to match the respective property's data type. ASP.NET will bind the data on post back. Additionally ViewModel is complex, so you can post a list of ViewRow (for multiple record updates). To bind this, your JSON object needs to have the ServiceDetails property that contains an array of objects that in turn have properties of ServiceID, Name, YesSelected, etc.
A collection of services in your viewmodel should do it, the Selected bool of course would represent the yes/no option and probably be bound to a checkbox.
public class ViewModel
{
public IList<Service> Services {get;set;}
}
public class Service
{
public bool Selected {get;set;}
public DateTime LastDate {get;set;}
public DateTime ProposedDate {get;set;}
}

Code First Entity / MVC4 - why aren't my models hydrated?

I can not figure out what I'm doing wrong here. New to MVC and new to Entity, so I know that's holding me back. Any time I call up AuthUser, AuthRole is always nothing, so I end up doing something like:
authuser.AuthRole = db.AuthRoleSet.Find(2) 'AuthRoleID of 2 = User
This just feels clunky to me. How do I get my property to actually get the role with the user?
Here's my class structure:
Public Class AuthUser
'Class Globals
Dim db As New AuthUserContext
'Properties
Public Property AuthUserID() As Integer
<Required()> _
<Display(Name:="User Name")> _
<DomainUserValidation()> _
Public Property UserName() As String
<Display(Name:="Current Role")> _
Public Property AuthRole As AuthRole
End Class
Public Class AuthRole
Public Property AuthRoleID() As Integer
<Required()> _
<Display(Name:="Role Name")> _
Public Property RoleName() As String
<Required()> _
<Display(Name:="Is Administrator")> _
Public Property isAdministrator() As Boolean
<Required()> _
<Display(Name:="Is Active")> _
Public Property isActive() As Boolean
<Required()> _
Public Property AuthUser As ICollection(Of AuthUser)
End Class
Public Class AuthUserContext
Inherits DbContext
Public Property AuthUserSet() As DbSet(Of AuthUser)
Public Property AuthRoleSet() As DbSet(Of AuthRole)
End Class
You have 2 options (sorry c# syntax):
1 - Lazy load AuthRole when you need it - for this, your AuthRole property needs to be declared as virtual
public virtual AuthRole {get;set;}
Now, when/if you try to access AuthRole, EF will get it from database.
For this to work you need to have DbContext.Configuration.LazyLoadEnabled = true
Another alternative is to eager load it by using a query like this:
var myUserWithRole = myContext.AuthUsers.Include("AuthRole").FirstOrDefault(x=>x.Id == userId);
This will get the user and the role from the database.

Select Specific Fields With Condition And Convert to List in Entity Framework

This is my table structure:
Partial Public Class KeyTable
Public Property KeyID As Long
Public Property ServiceName As String
Public Property Pricing As Nullable(Of Integer)
Public Property Active As Nullable(Of Boolean)
Public Property Description As String
Public Property Created As Nullable(Of Date)
End Class
This is a class I have
Public Class Service
Public KeyID As Double
Public ServiceName As String
End Class
I want to select the following fields
Select KeyID, ServiceName from KeyTable where Created= GivenDate
And convert the results to List (Of Service)
Here's what I tried so far:
Using db As New ServicesEntities()
Dim x = (From e1 In db.KeyTables Where e1.Created = sc Select e1.KeyID,e1.ServiceName).ToList()
End Using
You can try the following:
Using _DB As New ServicesEntities()
Dim _Services As List(Of Service) = (From e1 In _DB.KeyTables Where e1.Created = sc).ToList().ConvertAll(Function(Record) New Service With{.KeyID = Record.KeyId, ServiceName = Record.ServiceName }).ToList()
End Using

How can I pass a value entered in a texbox to a PartialViewResult?

I am creating an MVC app where the user can add items to their cart. They can also make partial payments on certain items so I have a TextBox for them to specify how much they want to pay. I am using an Ajax ActionLink to handle the Update/Add to cart actions so that I can increment the cart count without refreshing the screen using a partial view. My issue is that I can't find a way to pass in or access the value entered in the TextBox to my PartialViewResult function.
Here is my Model...
Public Class StudentSchoolFee_Transaction
Public Property SchoolFeeId As Integer
Public Property Title As String
Public Property Price As Decimal
Public Property AmountDue As Decimal
<DisplayFormat(ApplyFormatInEditMode:=True, DataFormatString:="{0:C2}")>
Public Property Amount As Decimal
Public Property Description As String
Public Property AcceptPartialPayment As Boolean
Public Property StudentId As Integer
Public Property TransactionId As Integer
End Class
Public Class AssignedFeesModel
Public Property StudentId As Integer
Public Property StudentNumber As Long
Public Property SiteId As String
Public Property SelectedSchoolFeeId As Integer
Public Property SelectedAcceptPartial As Boolean
Public Property SelectedAmountDue As Decimal
Public Property SelectedAmount As Decimal
Public Property SelectedTransactionId As Integer
Public Property AssignedFeesCol As System.Collections.Generic.List(Of StudentSchoolFee_Transaction)
Public Sub New()
End Sub
Public Sub New(ByVal _Deliver As EMS.Grid.Deliver, ByVal _StudentId As String)
Dim SelectedStudent As New Library.Student(_Deliver, _StudentId)
AssignedFeesCol = New System.Collections.Generic.List(Of StudentSchoolFee_Transaction)
StudentId = SelectedStudent.Id
StudentNumber = SelectedStudent.StudentNumber
SiteId = SelectedStudent.SiteId
'Load AssignedFeesCol
End Sub
End Class
Here are my initial load ActionResult and my AddAssignedFee PartialViewResult to refresh the cart count...
Function AssignedFees(ByVal StudentId As String, Optional ByVal ErrorMessage As String = "") As ActionResult
Dim oDeliver As New EMS.Grid.Deliver
oDeliver.UDLNameOrConnString = ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
Dim m As New AssignedFeesModel(oDeliver, StudentId)
Dim stu As New Library.MealHistoryDB.Student(oDeliver, m.StudentNumber, UserSession.GetSession.DistrictId)
Return View(m)
End Function
Public Function AddAssignedFee(ByVal StudentId As Integer, ByVal SchoolFeeId As Integer, ByVal SelectedAmount As Decimal) As PartialViewResult
Dim oDeliver As New EMS.Grid.Deliver
oDeliver.UDLNameOrConnString = ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString
With New Library.Ecommerce.SchoolFee(oDeliver, SchoolFeeId)
.AddToCart(oDeliver, UserSession.GetSession.ParentId, StudentId, SelectedAmount)
End With
Return PartialView("_CartButton") ', New Global.MSM.mobile.CartButton())
End Function
And here are my Ajax action links, the first is for Adding an item with no Amount specified and it works. The second is for Updating an item that can have an partial payment Amount and I can't find a way to pass the amount to the PartialViewResult.
#Ajax.ActionLink("Add", "AddAssignedFee", "Parent", New With {.StudentId = currentItem.StudentId, .SchoolFeeId = currentItem.SchoolFeeId, .SelectedAmount = currentItem.Amount}, New AjaxOptions() With {.HttpMethod = "POST", .InsertionMode = InsertionMode.Replace, .UpdateTargetId = "btnCartContainer"}, New With {.class = "button"})
#Ajax.ActionLink("Update", "AddAssignedFee", "Parent", New With {.StudentId = currentItem.StudentId, .SchoolFeeId = currentItem.SchoolFeeId, .SelectedAmount = currentItem.Amount}, New AjaxOptions() With {.HttpMethod = "POST", .InsertionMode = InsertionMode.Replace, .UpdateTargetId = "btnCartContainer"}, New With {.class = "button"})
I have also tried ".SelectedAmount = Model.SelectedAmount" for the Update link but I can't seem to find a way to pass the entered Amount to the PartialViewResult.
Any suggestions?
Thank you!
Lindsay
you might try doing an ajax call
$('.Link').on('click', function(){
$.ajax({
url: "#(Url.Action("AddAssignedFee", "Controller")",
type: "POST",
data: { textValue: $('.PaymentAmount').val(), data2: 'data2' }
cache: false,
async: true,
success: function (result) {
$(".Content").html(result);
}
});
});
Hopefully this helps

Saving a nested collection with MVC 3, EF 4.1, DbContext, and AutoMapper

I am having difficulty getting a nested collection (Tags in my case) to commit back to the database after being passed into my controller. I am using EF 4.1 with the DbContext API, MVC 3, and Automapper.
My Models:
Partial Public Class Proposal
Public Property Id As Integer
Public Property Memo As String
Public Property EntryDate As Nullable(Of Date)
Public Overridable Property CategoryTags As ICollection(Of CategoryTag) = New HashSet(Of CategoryTag)
End Class
Public Class ProposalViewModel
Public Property Id As Integer
<DataType(DataType.MultilineText)>
Public Property Memo As String
<DisplayFormat(ApplyFormatInEditMode:=True, DataFormatString:="{0:d}")>
Public Property EntryDate As Nullable(Of Date)
Public Overridable Property CategoryTags As ICollection(Of CategoryTag) = New HashSet(Of CategoryTag)
End Class
My view uses the code from the following post to add tags: http://jarrettmeyer.com/post/2995732471/nested-collection-models-in-asp-net-mvc-3. Essentially the tags are created by adding INPUT elements with their name attribute set to "CategoryTag[0].Id", "CategoryTag[1].Id" etc... and the value of those inputs are valid Ids for Tags in my database
Lastly, my POST code:
<HttpPost()>
Public Function Edit(ByVal pvm As ProposalViewModel) As ActionResult
Dim p As New Proposal
p = AutoMapper.Mapper.Map(Of ProposalViewModel, Proposal)(pvm)
If (ModelState.IsValid) Then
db.Entry(p).State = EntityState.Modified
db.SaveChanges()
Return RedirectToAction("Index")
Else
Return View(pvm)
End If
End Function
The pvm object is returned to my controller with the values set as I would want them to be. If I add two tags in run-time, then it has two CategoryTag objects in it's collection with the appropriate IDs. The problem is that on my call to SaveChanges, the corresponding records are not created in my many-to-many relation table (ProposalCategoryTag in this case).
Any idea what I'm doing wrong?
UPDATE:
I did not find anything on this, and have resorted to doing it manually like below. I dislike this method, but it works.
<HttpPost()>
Public Function Edit(ByVal pvm As ProposalViewModel) As ActionResult
Dim p As New Proposal
Dim tempTag As CategoryTag
p = AutoMapper.Mapper.Map(Of ProposalViewModel, Proposal)(pvm)
If (ModelState.IsValid) Then
db.Proposals.Attach(p)
db.Entry(p).Collection("CategoryTags").Load()
For Each ct As CategoryTag In pvm.Tags
tempTag = db.CategoryTags.Find(ct.Id)
If tempTag Is Nothing Then
Continue For
End If
If p.CategoryTags.Contains(tempTag) Then
Continue For
End If
p.CategoryTags.Add(tempTag)
Next
db.Entry(p).State = EntityState.Modified
db.SaveChanges()
Return RedirectToAction("Index")
Else
Return View(pvm)
End If
End Function
UPDATE:
I did not find anything on this, and have resorted to doing it manually like below. I dislike this method, but it works.
<HttpPost()>
Public Function Edit(ByVal pvm As ProposalViewModel) As ActionResult
Dim p As New Proposal
Dim tempTag As CategoryTag
p = AutoMapper.Mapper.Map(Of ProposalViewModel, Proposal)(pvm)
If (ModelState.IsValid) Then
db.Proposals.Attach(p)
db.Entry(p).Collection("CategoryTags").Load()
For Each ct As CategoryTag In pvm.Tags
tempTag = db.CategoryTags.Find(ct.Id)
If tempTag Is Nothing Then
Continue For
End If
If p.CategoryTags.Contains(tempTag) Then
Continue For
End If
p.CategoryTags.Add(tempTag)
Next
db.Entry(p).State = EntityState.Modified
db.SaveChanges()
Return RedirectToAction("Index")
Else
Return View(pvm)
End If
End Function

Resources