How to get the value the foreign key represents MVC4 - database

Currently, I have model which represents a table within my database.
public partial class Booking
{
public int BookingId { get; set; }
public string BookingFirstname { get; set; }
public string BookingSurname { get; set; }
public string BookingEmail { get; set; }
public string BookingMobileTel { get; set; }
public string BookingHomeTel { get; set; }
public int BookingAge { get; set; }
public int BookingPassengers { get; set; }
public int DepartureId { get; set; }
public int ArrivalId { get; set; }
}
DepartureId and ArrivalId are foreign keys of two other tables.
public partial class Departure
{
public int DepartureId { get; set; }
public string DepartureName { get; set; }
}
public partial class Arrival
{
public int ArrivalId { get; set; }
public int DepartureId { get; set; }
public string ArrivalName { get; set; }
}
I want to be able to get the Arrival Name and Departure Name from the option selected when the user submits a form from the Book View.
This is currently the [HttpPost] Book Action Result:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Book(Booking bk)
{
List<Departure> departures = new List<Departure>();
List<Arrival> arrivals = new List<Arrival>();
using (BookingEntities db = new BookingEntities())
{
departures = db.Departures.OrderBy(a => a.DepartureName).ToList();
if (bk != null && bk.DepartureId > 0)
{
arrivals = db.Arrivals.Where(a => a.DepartureId.Equals(bk.DepartureId)).OrderBy(a => a.ArrivalName).ToList();
}
}
ViewBag.DepartureId = new SelectList(departures, "DepartureId", "DepartureName", bk.DepartureId);
ViewBag.ArrivalId = new SelectList(arrivals, "ArrivalId", "ArrivalName", bk.ArrivalId);
string emailTo = bk.BookingEmail;
string emailBody = "Thank you for Booking with Callum Airways, " + bk.BookingFirstname + " " + bk.BookingSurname + ".\n" +
"Here is confirmation that your booking was a success. We have listed the information you entered into this email.\n" +
"Email: " + bk.BookingEmail + ",\n" +
"Mobile Tel: " + bk.BookingMobileTel + ",\n" +
"Home Tel: " + bk.BookingHomeTel + ",\n" +
"Age: " + bk.BookingAge + ",\n" +
"Number of Passengers: " + bk.BookingPassengers + ".\n\n" +
// Departure and Arrival Names
"If you want to review/delete your booking please register an account on ************.";
// All the other booking information.
using (BookingEntities db = new BookingEntities())
{
if (ModelState.IsValid)
{
db.Bookings.Add(bk);
db.SaveChanges();
ModelState.Clear();
bk = null;
MailAddress from = new MailAddress("*************#gmail.com");
MailAddress to = new MailAddress(emailTo);
MailMessage message = new MailMessage(from, to);
message.Subject = "Booking Confirmation - ********";
message.Body = emailBody;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.Timeout = 10000;
smtp.DeliveryMethod = SmtpDeliveryMethod.Network;
smtp.Credentials = new System.Net.NetworkCredential("*********************", "*******");
smtp.EnableSsl = true;
smtp.Send(message);
}
}
return View("~/Views/Home/Index.cshtml", bk);
}
I've been able to get the value of BookingFirstname and others but because there is just the foreign key not the name in the Booking Class. I'm not sure how I can get ArrivalName and DepartureName.

Arrival arrival = new Arrival();
arrival = db.Arrival.Where(w => w.ArrivalId.Equals(bk.ArrivalId).FirstOrDefault();
ViewBag.ArrivalName = arrival.ArrivalName;
Departure departure = new Departure();
departure = db.Departure.Where(w => w.DeaId.Equals(bk.ArrivalId).FirstOrDefault();
ViewBag.DepartureName = departure.DepartureName;

Related

Always getting null value when send object with fromData other value from React

I have send a formData from react app with some value and image files and i also want to send a obj with same formData on .net core api
Here is my class
[Bind]
public class ServiceInfo
{
public int id { get; set; }
[NotMapped]
public IFormFile[] ImgFile { get; set; }
[NotMapped]
public IFormFile ImgFilen { get; set; }
//public int { get; set; }
public string title { get; set; }
public string serImg1 { get; set; }
public string serImg2 { get; set; }
public string serImg3 { get; set; }
public string serImg4 { get; set; }
public int serCategoryId { get; set; }
public SerCategory serCategory { get; set; }
public string time { get; set; }
public string location { get; set; }
public string serviceClose { get; set; }
public string serviceOpen { get; set; }
public int CompanyInfoId { get; set; }
public virtual CompanyInfo companyInfo { get; set; }
public string serviceDetails { get; set; }
public string offeredServices { get; set; }
public bool active { get; set; }
public bool status { get; set; }
public string extraServices { get; set; }
public string whyUs { get; set; }
}
.net core controler:
serCategory always getting null
[Route("PotService")]
[HttpPost]
public IActionResult Post([FromForm] ServiceInfo service)
{
//using (MemoryStream stream = new MemoryStream())
//{
// ImgFile.CopyToAsync(stream);
// service.Data = stream.ToArray();
//}
if (string.IsNullOrWhiteSpace(_rootPath.WebRootPath))
{
_rootPath.WebRootPath = Path.Combine(Directory.GetCurrentDirectory(), "Images");
}
string uploadsFolder = Path.Combine(_rootPath.WebRootPath);
int index = 0;
foreach (var item in service.ImgFile)
{
index++;
if (item != null)
{
var uniqueFileName = service.title.ToString()+index.ToString()+ DateTime.Now.ToString("ddMMyyy") + "_" + item.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
switch (index)
{
case 1 :
service.serImg1 = uniqueFileName;
break;
case 2:
service.serImg2 = uniqueFileName;
break;
case 3:
service.serImg3 = uniqueFileName;
break;
case 4:
service.serImg4 = uniqueFileName;
break;
}
}
}
//bool result = _serManager.AddService(service);
foreach (var item in service.ImgFile)
{
if (item != null)
{
var uniqueFileName = service.title.ToString() + index.ToString() + DateTime.Now.ToString("ddMMyyy") + "_" + item.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
item.CopyTo(fileStream);
}
}
}
return Ok(true);
}
And react code :
const formData = new FormData();
formData.append("id", 0);
formData.append("CompanyInfoId", activeComId);
formData.append("title", data.title);
formData.append("time", "");
formData.append("location", data.location.value);
formData.append("serviceClose", data.serviceClose.value);
formData.append("serviceOpen", data.serviceOpen);
formData.append("serviceDetails", data.serviceDetails);
formData.append("serCategoryId", data.serType.id);
formData.append("serCategory", data.serType);
formData.append("offeredServices", data.offeredServices);
formData.append("active", false);
formData.append("status", false);
formData.append("extraServices", data.extraServices);
formData.append("whyUs", data.whyUs);
formData.append("ImgFile", data.serImg1);
formData.append("ImgFile", data.serImg2);
formData.append("ImgFile", data.serImg3);
formData.append("ImgFile", data.serImg4);
for (const [key, value] of formData.entries()) {
console.log(key, value);
}
console.log(data.serType);
const res = await fetch(serPost, {
method: "POST",
body: formData,
});

Pass Id From One Model to Another Model (with View Models) In .NET Core

I have 2 models and their view models:
public class Location:BaseEntity
{
[Display(Name = "Title")]
[Required(ErrorMessage = "Required")]
[MaxLength(200)]
public string Title { get; set; }
public long? ParentId { get; set; }
[Display(Name = "IsDeleted")]
public bool IsDeleted { get; set; }
[Display(Name = "IsActive")]
public bool IsActive { get; set; }
[ForeignKey("ParentId")]
public Location Parent { get; set; }
public ICollection<UserInfo.UserInfo> UserInfos { get; set; }
}
And this is its view model:
public class UserLocationViewModel
{
[Required(ErrorMessage = "Required")]
public string Title { get; set; }
public long LocationId { get; set; }
}
The second one is this, and its view model has "Location Id":
public class UserInfo : BaseEntity
{
public long UserPackageId { get; set; }
[Display(Name = "Address")]
[MaxLength(350)]
public string Address { get; set; }
public ICollection<PackageFile> PackageFiles { get; set; }
[ForeignKey("UserPackageId")]
public UserPackage UserPackage { get; set; }
[ForeignKey("LocationId")]
public Location.Location Location { get; set; }
}
I have some method .there are 2 table. but I want to create a form with 2 view model. how can I pass LocationId from table "Location" to another model "UserInfo"
This is my service:
public async Task<(UserInfoType UserInfoType, long UserInfoId)> CreateFirstStartUserInfoByUser(CreateFirstStartUserInfoViewModel firstStartUserInfo, long userId)
{
if (!await IsPackagePurchasedByUser(userId, firstStartUserInfo.PackageId))
return (UserInfoType.NotFound, 0);
var userPackageId = await _packageRepository.GetUserPackageIdByUserIdAndPackageId(userId, firstStartUserInfo.PackageId);
if (userPackageId <= 0)
return (UserInfoType.NotValid, 0);
if (await _packageRepository.IsExistUserInfoByUserPackageId(userPackageId))
{
long userInfoId = 0;
for (int i = 1; i <= 3; i++)
{
EditFirstStartUserInfoViewModel editFirstStartUserInfo = new EditFirstStartUserInfoViewModel()
{
PackageId = firstStartUserInfo.PackageId,
Address = firstStartUserInfo.Address,
DayOfBirth = firstStartUserInfo.DayOfBirth,
Goal = firstStartUserInfo.Goal,
Job = firstStartUserInfo.Job,
Marriage = firstStartUserInfo.Marriage,
MonthOfBirth = firstStartUserInfo.MonthOfBirth,
Sex = firstStartUserInfo.Sex,
UserPackageId = userPackageId,
UserInfoId = await _packageRepository.GetUserInfoIdByUserPackageIdAndUserInfoSituation(userPackageId, i),
YearOfBirth = firstStartUserInfo.YearOfBirth,
LocationId = await GetUserLocationIdForCreate(firstStartUserInfo)
};
await EditFirstStartUserInfoByUser(editFirstStartUserInfo, userId);
if (i == 1)
userInfoId = editFirstStartUserInfo.UserInfoId;
}
if (userInfoId <= 0)
return (UserInfoType.NotValid, 0);
return (UserInfoType.Success, userInfoId);
}
// this id is userInfo id
long id = 0;
for (int i = 1; i <= 3; i++)
{
UserInfo UserInfo = new UserInfo()
{
UserPackageId = userPackageId,
Address = firstStartUserInfo.Address.SanitizeText(),
Job = firstStartUserInfo.Job.SanitizeText(),
DayOfBirth = firstStartUserInfo.DayOfBirth,
MonthOfBirth = firstStartUserInfo.MonthOfBirth,
YearOfBirth = firstStartUserInfo.YearOfBirth,
Sex = firstStartUserInfo.Sex,
Marriage = firstStartUserInfo.Marriage,
Goal = firstStartUserInfo.Goal.SanitizeText(),
UserInfoSituation = (UserInfoSituation?)i,
EditExpireDate = null,
LocationId =????????
};
await _packageRepository.CreateUserInfo(UserInfo);
await _packageRepository.SaveChanges();
if (i == 1)
id = UserInfo.Id;
}
if (id <= 0)
return (UserInfoType.NotValid, 0);
return (UserInfoType.Success, id);
}
This is my controller on post method:
var state = await _packageService.GetStateForUserInfo();
ViewData["State"] = state;
var firstLocationId = state.FirstOrDefault().LocationId;
var city = await _packageService.GetCityForUserInfo(firstLocationId);
ViewData["City"] = city;

INSERT statement conflicted with foreign key constraint - SQL Server/Entity Framework Core

I get this error in my .NET Core 3.1 app:
The INSERT statement conflicted with the FOREIGN KEY constraint "FK_DiaryDiaryEntry". The conflict occurred in database "xxxxxx", table "dbo.Diaries", column 'Id'.
I can't see anything wrong with the tables themselves.
public partial class Diaries
{
public long Id { get; set; }
public string CoverImage { get; set; }
public short Year { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public long ChildId { get; set; }
public Children Child { get; set; }
public ICollection<DiaryEntries> DiaryEntries { get; set; }
}
public partial class DiaryEntries
{
public long Id { get; set; }
public DateTime Date { get; set; }
public string Content { get; set; }
public long DiaryId { get; set; }
public Diaries Diary { get; set; }
public ICollection<Images> Images { get; set; }
}
My code? Probably an entirely different matter.
This is the code that generates the error.
[HttpPost("CreateYear/{id}")]
public async Task<IActionResult> CreateYearOfEntries([FromRoute] int id)
{
// The id is the ID of an existing diary
// Make sure the diary does exist first and that it belongs to the current logged-in user
var diary = _diaryRepository.Find(id);
if (diary == null) return NotFound();
var year = diary.Result.Year;
if (await _diaryEntryRepository.OwnerIsLoggedIn(LoggedInUser.ParentId, id))
{
var noOfDays = DateTime.IsLeapYear(year) ? 366 : 365;
var i = 0;
for (; i < noOfDays; i++)
{
var date = new DateTime(year, 1, 1).AddDays(i);
var newDiaryEntry = new DiaryEntries()
{
Content = " ",
Date = date,
DiaryId = diary.Id
};
await _diaryEntryRepository.Add(newDiaryEntry);
}
return Ok();
}
return NotFound();
}
public class DiaryEntryRepository : IDiaryEntryRepository
{
private readonly ApplicationDbContext _context;
public DiaryEntryRepository(ApplicationDbContext context)
{
_context = context;
}
public async Task<DiaryEntries> Add(DiaryEntries diaryEntry)
{
await _context.DiaryEntries.AddAsync(diaryEntry);
await _context.SaveChangesAsync();
return diaryEntry;
}
}

How can I auto-update the int ModifiedBy property on a Entity with UserId in Entity Framework 4 when saving?

I am using Simple Membership and a UserProfile table that maintains UserId and UserName:
public partial class UserProfile
{
public UserProfile()
{
this.webpages_Roles = new List<webpages_Roles>();
}
public int UserId { get; set; }
public string UserName { get; set; }
public virtual ICollection<webpages_Roles> webpages_Roles { get; set; }
}
With Entity Framework I am running the following which is inside my Context:
public partial class UowContext : DbContext
// code to set up DbSets here ...
public DbSet<Content> Contents { get; set; }
private void ApplyRules()
{
var r1 = new Random();
var r2 = new Random();
foreach (var entry in this.ChangeTracker.Entries()
.Where(
e => e.Entity is IAuditableTable &&
(e.State == EntityState.Added) ||
(e.State == EntityState.Modified)))
{
IAuditableTable e = (IAuditableTable)entry.Entity;
if (entry.State == EntityState.Added)
{
e.CreatedBy = // I want to put the integer value of UserId here
e.CreatedDate = DateTime.Now;
}
e.ModifiedBy = // I want to put the integer value of UserId here
e.ModifiedDate = DateTime.Now;
}
}
Here is the schema showing how user information is stored. Note that I store the integer UserId and not the UserName in the tables:
public abstract class AuditableTable : IAuditableTable
{
public virtual byte[] Version { get; set; }
public int CreatedBy { get; set; }
public DateTime CreatedDate { get; set; }
public int ModifiedBy { get; set; }
public DateTime ModifiedDate { get; set; }
}
Here's an example of a controller action that I use:
public HttpResponseMessage PostContent(Content content)
{
try
{
_uow.Contents.Add(content);
_uow.Commit();
var response = Request.CreateResponse<Content>(HttpStatusCode.Created, content);
return response;
}
catch (DbUpdateException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.Conflict, ex);
}
}
I then have:
public class UowBase : IUow, IDisposable
{
public UowBase(IRepositoryProvider repositoryProvider)
{
CreateDbContext();
repositoryProvider.DbContext = DbContext;
RepositoryProvider = repositoryProvider;
}
public IRepository<Content> Contents { get { return GetStandardRepo<Content>(); } }
and:
public class GenericRepository<T> : IRepository<T> where T : class
{
public GenericRepository(DbContext dbContext)
{
if (dbContext == null)
throw new ArgumentNullException("An instance of DbContext is required to use this repository", "context");
DbContext = dbContext;
DbSet = DbContext.Set<T>();
}
public virtual void Add(T entity)
{
DbEntityEntry dbEntityEntry = DbContext.Entry(entity);
if (dbEntityEntry.State != EntityState.Detached)
{
dbEntityEntry.State = EntityState.Added;
}
else
{
DbSet.Add(entity);
}
}
How can I determine the UserId from inside of my Context so I can populate the Id in my tables?
In Code you will have UserName with you through:
HttpContext.Current.User.Identity.Name
you can than query UserProfile table against that Name and get the UserId from there and than assign it to ModifiedBy attribute.
Make sure that you query UserProfile table outside the foreach loop :)

how to combine the result from differentviews to IQueryable<T>

i have a list of PlanItems bind to telerik RadGrid and have two views retrieves the result.Each view get different data so how can i get that data into IQueryable
public class PlanItems
{
public int Id{get; set;}
public string Name { get; set; }
public string HV { get; set; }
public string StNumber { get; set; }
public string LDNumber { get; set; }
public string MSId { get; set; }
public string CreatedBy { get; set; }
public string Type { get; set; }
}
I have 2 different views vw_Boys ,vw_Girls and Student Entity
first i got boys_Id and Girls_Id from student Entity
public IQuerable<PlanItems> GetAllStudents()
{
var Id = from v in context.Student
.Include("SBoy")
.Include("SGirl")
where v.CreatedBy_Id == user.Id
select v;
var temp = unp.Select(a=>a.SBoy.boys_Id).Distinct();
var temp1 = unp.Select(a => a.SGirl.girls_Id).Distinct();
var vwboys = from nv in context.vw_boys
where(temp.Contains(nv.SId))
select nv;
var vwgirls= from nv in context.vw_girls
where (temp1.Contains(nv.GId))
select nv;
var Boysresult = from n in vwboys
select new PlanItems
{
Id = n.SId,
Name = n.Name,
HV = n.HV,
StNumber = n.SNumber,
LDNumber = n.LineNumber,
MSId = n.MasterId,
CreatedBy = n.USerName,
Type = n.SubjectType
};
var GirlsResult = from n in vwgirls
select new UnplannedItems
{
Id = n.GiId,
Name = n.Name,
HV = n.GV,
StNumber = n.SujNumber,
LDNumber = n.Lid,
MSId = n.MasterId,
CreatedBy = n.USerName,
Type = n.SubjectType
};
}
my telerikGrid sample
<telerik:GridViewDataColumn Header="StudentID" IsReadOnly="True" DataMemberBinding="{Binding ID, Mdde=OneWay}" />
how can i return the result from above method..how can i combine the result to one.
I would do it something like this.
Add a new property to you class like this. Because you might have to seperate the boys from the girls in a other case:
public class PlanItems
{
public int Id{get; set;}
public string Name { get; set; }
public string HV { get; set; }
public string StNumber { get; set; }
public string LDNumber { get; set; }
public string MSId { get; set; }
public string CreatedBy { get; set; }
public string Type { get; set; }
//new property
public bool IsUnplanned { get; set; }
}
The use a concat between them like this:
var result= (
from n in vwboys
select new PlanItems
{
Id = n.SId,
Name = n.Name,
HV = n.HV,
StNumber = n.SNumber,
LDNumber = n.LineNumber,
MSId = n.MasterId,
CreatedBy = n.USerName,
Type = n.SubjectType,
IsUnplanned=false
}
).Concat
(
from n in vwgirls
select new PlanItems
{
Id = n.GiId,
Name = n.Name,
HV = n.GV,
StNumber = n.SujNumber,
LDNumber = n.Lid,
MSId = n.MasterId,
CreatedBy = n.USerName,
Type = n.SubjectType,
IsUnplanned=true
}
);
Hope this helps
You can union 2 different IQueryable using union extension method :
here's an example
I am not an expert in wpf, but looking at the solution I think you can use a parent class for both Boys and Girls and then add to a list of that class.
lets say both Boy and Girl classes are inherited from Person class, then create
List<Person> personList = new List<Person>()
and add Boys and Girls into this list.
I am not sure whether this is the solution you need

Resources