Web ApI Entity Framework (Code First) Value not appearing in database - sql-server

My database will run correctly, and I can input the data manually via SQL Server, however, when I try and pass the value in via my API (testing using Postman), the value won't pass into the database, it appears as "NULL".
I have a reports and a bookings tables.
This is the code for the reports:
public class Report
{
public Report()
{
Injuries = new List<Injury>();
this.Bookings = new HashSet<Booking>();
}
public int Id { get; set; }
public string Club1 { get; set; }
public string Club2 { get; set; }
public virtual ICollection<Injury> Injuries { get; set; }
public virtual ICollection<Booking> Bookings { get; set; }
}
Bookings:
public class Booking
{
//public Booking()
//{
// Reports = new List<Report>();
//}
public int Id { get; set; }
public string Club { get; set; }
public string PlayerName { get; set; }
public string PlayerNumber { get; set; }
public string Reason { get; set; }
public string Description { get; set; }
//public int? Report_Id { get; set; }
public Nullable<int> Report_Id { get; set; }
public virtual Report Report { get; set; }
//public virtual ICollection<Report> Reports { get; set; }
}
Controller:
//POST: api/Reports
[ResponseType(typeof(Report))]
public async Task<IHttpActionResult> PostReport(Report report)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Reports.Add(report);
await db.SaveChangesAsync();
return CreatedAtRoute("DefaultApi", new { id = report.Id }, report);
}
I put the test information via Postman:
I'm not sure why Report_Id is showing as it's not required, however, Report_Id1 is the field that is connecting the Report and Booking together.

Since your foreign key doesn't follow convention (ReportId), you need to use the annotation [ForeignKey] or a fluent api configuration:
modelBuilder.Entity<Booking>()
.HasRequired(b => b.Report)
.WithMany(b => b.Bookings)
.HasForeignKey(p => p.Report_Id);
That is why EF is adding the second Report_ID1. https://msdn.microsoft.com/en-us/data/hh134698.aspx

Related

EF core order by navigation property

I have an entity relationship like this.
public class Provider
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<ProviderPod> ProviderPods { get; set; } = new List<ProviderPod>();
}
public class ProviderPod
{
public int Id { get; set; }
public int ProviderId { get; set; }
public int PodId { get; set; }
public virtual Provider Provider { get; set; }
public virtual Pod Pod { get; set; }
}
public class Pod
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<ProviderPod> ProviderPods { get; set; } = new List<ProviderPod>();
}
I need to order the 'Provider' entity by it's navigation property ProviderPods' "Name" separated by a comma. Something like this
IQueryable<Provider> entityQuery = context.Providers.AsQueryable();
//Need to enter Appropriate query below
entityQuery = entityQuery.OrderByDescending(x => string.Join(", ", x.ProviderPods.Select(y => y.Pod.Name)));
var list = entityQuery.Take(12).ToList();
What would be the best way to achieve this ordering?

Update database schema to allow multiple users

I'm working on an ASP.net Web API application and would like to allow multiple users to have access to their own data without changing the database schema too much.
My tables look a little like this:
public class Asset
{
public string Name { get; set; }
[Required]
public int Id { get; set; }
public string AssetTag { get; set; }
public string Serial { get; set; }
public int Model { get; set; }
}
public class Organisation
{
[Required]
public int Id { get; set; }
[Required]
public int DefaultLocation { get; set; }
public location Location { get; set; }
public string Name { get; set; }
public string Phone { get; set; }
public string Contact { get; set; }
}
public class AssetModel
{
public string Name { get; set; }
[Required]
public int Id { get; set; }
public int CategoryId { get; set; }
public int ManufacturerId { get; set; }
public string ModelNumber { get; set; }
}
*fields omitted for brevity
Each user should be able to create their own assets / organisations / etc, but should not have access to any other users fields.
I'm yet to add authorization / authentication however I'm probably going to use token based auth as outlined here:
http://bitoftech.net/2014/06/09/angularjs-token-authentication-using-asp-net-web-api-2-owin-asp-net-identity/
Should this be as easy as tacking each users GUID onto each column and applying some logic? Or will I need to completely re-design the database?

Any obvious reason why my breeze entity child nodes won't expand?

I can't figure out why my child nodes are either null or have a count of 0, even though there's associated data in the db.
Parent Class "Project"
public partial class Project
{
public Project()
public int Id { get; set; }
public string Name { get; set; }
public int ProjectOwnerId { get; set; }
public int CurrentMilestoneId { get; set; }
public int StatusId { get; set; }
public virtual Milestone CurrentMilestone { get; set; }
public virtual ProjectStatus Status { get; set; }
public virtual ICollection<ProjectContact> Contacts { get; set; }
public virtual ProjectAddress Address { get; set; }
}
Child node property "CurrentMilestone" comes back null
public partial class Milestone
{
public int Id { get; set; }
public int MasterMilestoneId { get; set; }
public string Name { get; set; }
public virtual MasterMilestone MasterMilestone { get; set; }
public virtual ICollection<Project> Projects { get; set; }
}
Child node property "Contacts" comes back with an array of 0, even though there's valid matching data.
public partial class ProjectContact
{
public int Id { get; set; }
public int ProjectId { get; set; }
public int PersonId { get; set; }
public string Title { get; set; }
public virtual Person Person { get; set; }
public virtual Project Project { get; set; }
}
Using the HotTowel angular/breeze I'm running this..
return EntityQuery.from("Projects")
.orderBy(orderBy)
.expand("currentMilestone.masterMilestone, projectOwnerCompany, contacts, address")
.using(self.manager).execute()
.then(querySucceeded, self._queryFailed);
function querySucceeded(data) {
projects = data.results;
return projects;
}
Controller:
[HttpGet]
public IQueryable<Project> Projects()
{
return _contextProvider.QueryAllReadOnly<Project>();
}
What's weird is some of them work, like Status works but leaseStatus doesn't (not shown, setup the same way) without expanding it.
Just to add more info, if I run this against the API, ..../Projects?$expand=Status%2CCurrentMilestone%2CLeaseStatus%2CCurrentMilestone%2FMasterMilestone%2CContacts%2CContacts%2FPerson&
In Fiddler the child nodes aren't expanded.
Figured it out..
Change the Controller from ReadOnly to non-readonly.
From
[HttpGet]
public IQueryable<Project> Projects()
{
return _contextProvider.QueryAllReadOnly<Project>();
}
To
[HttpGet]
public IQueryable<Project> Projects()
{
return _contextProvider.QueryAll<Project>();
}

Better way to create database for a pricing system

I need to create a price table system so I am going to create these three tables in my database.
PricingTable (ID, Name, ServiceID, Style)
PricingTablePackages (ID, PricingTable_ID, Title, Price, PricePerTime, Info, Flag, Link)
PricingTablePackagesFeatures (ID, PricingTablePackages_ID, Feature, Value, MoreInfo)
Here one PriceTable can hold more then one PricingTablePackages and one PricingTablePackage can hold more then one PricingTablePackagesFeature.
Is any way to design a better model? In a single database Table ?
I am going to create a MVC3 Model for those table so what is the best way to do this kind of DB Table in a MVC3 Model?
I would use public virtual variables for 'lazy-loading' values when you need them using Entity Framework:
(variable types may be off depending on exactly what you want for each variable)
public class PricingTablePackages
{
public int ID { get; set; }
public int PricingTableID { get; set; }
public virtual PricingTable PricingTable { get; set; }
public string Title { get; set; }
public decimal Price { get; set; }
public decimal PricePerTime { get; set; }
public string Info { get; set; }
public bool Flag { get; set; }
public string Link { get; set; }
}
public class PricingTablePackagesFeatures
{
public int ID { get; set; }
public int PricingTableID { get; set; }
public virtual PricingTable PricingTable { get; set; }
public string Feature { get; set; }
public string Value { get; set; }
public string MoreInfo { get; set; }
}
public class PricingTable
{
public int ID { get; set; }
public string Name { get; set; }
public int ServiceID { get; set; }
public virtual Service Service { get; set; } // if there is a Service class
public string Style { get; set; }
}

Subsonic 3.0.0.5 Migration Row Update

I want to update a table row and I have a following Code
void updatePrimaryPaymentAndSecondaryPaymentSourceTypes()
{
LookUpDetails lookUpDetail = new LookUpDetails();
var repo = new SimpleRepository("E2Lending", SimpleRepositoryOptions.RunMigrations);
lookUpDetail = repo.Single(80);
lookUpDetail.Col1Value = "My Checking Account";
repo.Update(lookUpDetail);
}
public class LookUpDetails
{
[SubSonicPrimaryKey]
public int LookUpDetailId {get; set;}
public int LookUpGroupId { get; set; }
public string Code { get; set; }
public int SortOrder { get; set; }
public string Col1Value { get; set; }
[SubSonicNullString]
public string Col2Value { get; set; }
[SubSonicNullString]
public string Col3Value { get; set; }
[SubSonicNullString]
public string Col4Value { get; set; }
[SubSonicNullString]
public string Col5Value { get; set; }
public DateTime CreatedOn { get; set; }
public string CreatedBy { get; set; }
public DateTime ModifiedOn { get; set; }
public string ModifiedBy { get; set; }
public Boolean IsActive { get; set; }
}
When I execute then repo.Update(lookUpDetail); shows me Null reference Exception.
Can you please tell me How I will be able to update a single record in a table?
Regards
I have the very same problem with very simple model class:
class Person
{
public long ID {get;set;}
public string Name { get; set;}
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection) {
Person toUpdate = Repository.All<Person>().Single(p => p.ID == id);
TryUpdateModel(toUpdate, collection.ToValueProvider());
Repository.Update(toUpdate); //throws nullreferenceexception
return RedirectToAction("Index");
}
stack trace:
at SubSonic.Query.Update.GetCommand()
at SubSonic.Query.Update.Execute()
at SubSonic.Repository.SimpleRepository.Update[T](T item)
at MvcApplication1.Controllers.PersonController.Edit(Int32 id, FormCollection collection)
in H:\...\Controllers\PersonController.cs:line 71"
My configuration: SubSonic 3, SQLite, empty database
I ran into this problem as well and I was able to download the latest SubSonic source and the issue was already fixed. Just open the SubSonic.Core project and do a build and replace your project's reference to SubSonic.Core.
Download Latest Source
http://github.com/subsonic/SubSonic-3.0
Boom - Repository Update works again!

Resources