Update database schema to allow multiple users - database

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?

Related

Change API response Object name (in Model) for Datagrid binding

I'm using WPF and still relatively new.
I haven't yet made the jump to MVVM, still trying to wrap my head around it.
I currently have a small app which extracts data from 4 different sources (at different times) and then displays it on a datagrid.
The issue is that the data model from the responses differs and I want to be able to easily use the same datagrid.
EG.
Datagrid binds to a model [zephyrPatientData]
Firstname : binds to firstName
last name: binds to lastName
ONE of the extractions has:
Firstname = firstName;
lastName = SURNAME.
Therefore if I use this data and try and bind to the datagrid, the LASTNAME firle is not filled as that model doesn't have lastName, it has surname.
Below: the datamodel that is working with the datagrid.
public class zephyrPatientData
{
public int CustomerID { get; set; }
public int ClaimID { get; set; }
public string ChemistID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string ClaimNumber { get; set; }
public bool concern { get; set; }
public int? InsCompID { get; set; }
public string InsCompName { get; set; }
public int? EmployerID { get; set; }
public string EmployerName { get; set; }
public string DateOfInjury { get; set; }
public string dateOfBirth { get; set; }
public string Address { get; set; }
public int? SuburbID { get; set; }
public string SuburbName { get; set; }
public string Postcode { get; set; }
public string custPhone { get; set; }
public int? claimTypeID { get; set; }
public string InvoiceTo { get; set; }
public string Comments { get; set; }
public string ClaimManager { get; set; }
public string Injury { get; set; }
public bool activeClaim { get; set; }
public string ClaimManagerEmail { get; set; }
public int? LawyerID { get; set; }
public string LawyerCompany { get; set; }
public double? outstandingScripts { get; set; }
public double? outstandingValue { get; set; }
public string dispenseConnected { get; set; }
public string dispenseID { get; set; }
}
Below: The Datamodel I want to work with the datagrid.
public class zDispensePatientData
{
public string id { get; set; }
public int clientNo { get; set; }
public string firstName { get; set; }
private string surname;
public string lastName
{
get
{
return surname;
}
set
{
surname = value;
}
}
public string title { get; set; }
public object licenseNo { get; set; }
public string sex { get; set; }
public object dateOfBirth { get; set; }
public object postalAddress { get; set; }
public object postalSuburb { get; set; }
public object postalState { get; set; }
public object postalPostCode { get; set; }
public string homeAddress { get; set; }
public string homeSuburb { get; set; }
public string homeState { get; set; }
public string homePostCode { get; set; }
public string phoneNumber { get; set; }
public string mobileNumber { get; set; }
public object faxNumber { get; set; }
public string email { get; set; }
public DateTime lastModified { get; set; }
public bool active { get; set; }
public bool deceased { get; set; }
}
As you can see...I TRIED to use the get;set; section of the [zDispensePatientData] however I have no idea how to use this correctly.
In reality in laman's terms I want it to read surname from the API response but then be accessible as lastName in for use in the Datagrid.
The reaons for this is that there will be another 4 [zDispensePatientData] (other names) and all will have different field names but in the end I need them to work in the same datagrid without changing the binding of every single datagrid column.
EDIT: Expanded the question:
So I appreciate the responses but I'm not exactly grasping how to get this done.
If I were to take away all the model fields and just leave... 3:
firstName
lastName
patientID
my task is to have 5 different models (from responses from API's) 'allocate' to my own model.
eg.
<my model>
public string id { get; set; }
public string lastName { get; set; }
public string firstName { get; set; }
<model API 1>
public string id { get; set; }
public string patientLastName { get; set; }
public string patientFirstName { get; set; }
<model API 2>
public string patientid { get; set; }
public string surname{ get; set; }
public string FIRSTNAME{ get; set; }
Any app will only ever have one connection ([dispenseType]).
So I guess what I need is checking the user dispenseType and then using the model from the API they are using.
Or is it possible to SET myModel based on the contents of the other models.
eg.
if
API1.firstName = null
myModel.firstName = api2.FIRSTNAME
My main issue is I don't know the concept or question to ask. If there is a pointer to the terminology of what I'm trying to achieve I'm happy to go out and learn it to implement it.
If the column in the DataGrid binds to a property named "LastName", you need to make sure that the type T in the IEnumerable<T> ItemsSource of the DataGrid has such a property.
So add one to the zDispensePatientData class like you have currently done:
public string LastName
{
get => surname;
set => surname = value;
}
Another option is to set or bind the ItemsSource to a an IEnumerable<ViewModel> where the ViewModel class has the properties that the DataGrid expects.
You would then translate each zephyrPatientData and/or zDispensePatientData object to a ViewModel, e.g.:
sourceCollection = zDispensePatientDatas
.Select(x => new ViewModel() { LastName = x.Surname } );
How to map properties of two different objects?
This question answers my question but was stated in a better way than I could

Manual Changes to Entity Framework Database causes error

I am fairly new to Entity Framework and C#, so I apologize if my ability to describe the problem is minimal.
I have a .NET Web Forms project hosted on Azure that uses Entity Framework to handle all the database tables. I recently had an issue that I was debugging and I created test records, which I removed once the issue was solved using Microsoft SQL Server Management Studio. Unfortunately, I now get the following error:
"The model backing the 'RegSysContext' context has changed since the database was created. Consider using Code First Migrations to update the database"
The RegSysContext class can be seen below.
From what I understand, this is caused by the metadata that Entity Framework uses not matching the database anymore. The data in the database is essential to keep, otherwise I would just wipe it and forget about it.
How can I solve this issue on the hosted web app, and how can I edit the database in the future without causing this problem?
Thanks in advance!
public class RegSysContext : DbContext
{
// Default Constructor for the context class
public RegSysContext() : base("RegSys")
{
}
// Properties of the context class
public DbSet<CustomerAccountMembership> AccountMembershipRecords { get; set; }
// For Organization Account functionality
public DbSet<RegSysAccount> RegSysAccounts { get; set; }
public DbSet<Subscription> Subscriptions { get; set; }
public DbSet<SubscriptionRecord> SubscriptionRecords { get; set; }
public DbSet<PaymentInfo> PaymentAccountInfoRecords { get; set; }
// For Auction functionality
public DbSet<Auction> auctions { get; set; }
public DbSet<AuctionItem> auctionItems { get; set; }
public DbSet<AuctionLot> auctionLots { get; set; }
public DbSet<AuctionDonation> auctionDontations { get; set; }
public DbSet<AuctionSale> auctionSales { get; set; }
public DbSet<ItemInAuctionRecord> itemInAuctionRecords { get; set; }
// For Event functionality
public DbSet<Event> events { get; set; }
public DbSet<EventParticipant> eventParticipants { get; set; }
public DbSet<RegistrationPeriod> registrationPeriods { get; set; }
public DbSet<RegType> regTypes { get; set; }
public DbSet<RegPrice> regPrices { get; set; }
public DbSet<EventCategory> EventCategories { get; set; }
//public DbSet<RegistrationConfig> regConfigs { get; set; }
//public DbSet<RegFormConfig> regFormConfigs { get; set; }
// For Organization functionality
public DbSet<Lodge> Lodges { get; set; }
// For Participant functionality
public DbSet<Participant> Participants { get; set; }
public DbSet<Charge> Charges { get; set; }
public DbSet<EventParticipantToParticipantLinker> EventParticipantLinks { get; set; }
// For System functionality
public DbSet<RegSysMessage> RegSysMessages { get; set; }
public DbSet<Transaction> Transactions { get; set; }
// For Trading Post functionality
public DbSet<Category> Categories { get; set; }
public DbSet<Product> Products { get; set; }
public DbSet<CartItem> ShoppingCartItems { get; set; }
public DbSet<ProductInventory> ProductInventories { get; set; }
public DbSet<TradingPost> TradingPosts { get; set; }
public DbSet<Order> Orders { get; set; }
public DbSet<OrderDetail> OrderDetails { get; set; }
public DbSet<ProductSale> ProductSales { get; set; }
public DbSet<SpecialOffer> SpecialOffers { get; set; }
}
Add this line to your constructor inside your RegSysContext class :
Database.SetInitializer<RegSysContext>(null);
What this line of code does it tells Entity Framework whether or not to create the database. Passing null into the IDatabaseInitializer strategy parameter, you basically disable the initialization of the database altogether (since it already exists)

Asp.net mvc using EntityFramework: loading Person by passing id is retrieving a Object but Object properties are null?

i am hanging for while and i dont understand one thing...I will try to explain my issue...
I have model(Table) called FeuerwehrPerson and the class looks like that:
public partial class FeuerwehrPerson
{
public FeuerwehrPerson()
{
this.BuchungenResultateList = new List<BuchungenResultate>();
this.Notenspiegel=new Notenspiegel();
this.Gemeinde=new Gemeinde();
}
public int FeuerwehrPersonId { get; set; }
public string Anrede { get; set; }
public string Vorname { get; set; }
public string Nachname { get; set; }
public System.DateTime Geburtstag { get; set; }
public string Strasse { get; set; }
public string Plz { get; set; }
public string Ort { get; set; }
public string Telefon { get; set; }
public int GemeindeId { get; set; }
public Nullable<int> NotenspielgelId { get; set; }
public virtual ICollection<BuchungenResultate> BuchungenResultateList { get; set; }
public virtual Gemeinde Gemeinde { get; set; }
public virtual Notenspiegel Notenspiegel { get; set; }
}
In Feuerwehrperson are 2 Foreign Keys
GemeindeId
NotenspiegelId
and both of them are holding some values for a specific FeuerwehrPerson.
Both Foreign Keys are not null in my FeuerehrPerson Table...
In my Controller i have a Edit Action...and i am searching for FeuerwehrPerson by id...thats working fine:
FeuerwehrPerson feuerwehrperson = db.FeuerwehrPerson.Find(id);
When i am checking the values by using add Watch of feuerwehrperson Object there are some empty properties which shouldn´t be empty
The Object property Gemeinde should contain some values but its empty...also for Notenspiegel Object should contain SeminarA=true, SeminarB=true, SeminarC=true, rest is false but everything is false also NotenspiegelId and GemeindeId...but the Foreign Key references in Feuerwehrperson are not null...but why is it empty????
Please help me...

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; }
}

ASP.NET MVC 3, SQL Server

First I'll show you what I do, and that there is. My project in ASP.NET MVC 3.
This is model for table Business.
[Table("Business")]
public class Business
{
[Key]
public long? BusinessId { get; set; }
public Int32 LegalTypeId { get; set; }
public Int16 BusinessTypeId { get; set; }
public Int64 OwnerId { get; set; }
public Int32 MainIndustryFieldId { get; set; }
public String NameNative { get; set; }
public String NameEnglish { get; set; }
public Byte[] Logo { get; set; }
public DateTime CreateDate { get; set; }
public virtual User Owner { get; set; }//It is Forign key with user table
}
[Table("User")]
public class User
{
[Key]
public Int64 UserId { get; set; }
public String UserName { get; set; }
public String LoweredUserName { get; set; }
public String FirstName { get; set; }
public String LastName { get; set; }
public String Email { get; set; }
public String LoweredEmail { get; set; }
public String Password { get; set; }
public String PasswordSalt { get; set; }
public String PasswordQuestion { get; set; }
public String PasswordAnswer { get; set; }
public Boolean IsApproved { get; set; }
public Boolean IsLocked { get; set; }
public DateTime LastActivityDate { get; set; }
public DateTime LastLoginDate { get; set; }
public DateTime CreateDate { get; set; }
public virtual Business Bussines { get; set; }
}
when I want to add information:
user.Business = new Business
{
OwnerId = user.UserId,
LegalTypeId = business.LegalTypeId,
BusinessTypeId = business.BusinessTypeId,
MainIndustryFieldId = business.MainIndustryFieldId,
NameNative = business.NameNative,
NameEnglish = business.NameEnglish,
Logo = business.Logo,
CreateDate = DateTime.Now
};
ctx.SaveChanges();
I get the following error:
Cannot insert explicit value for identity column in table 'Business'
when IDENTITY_INSERT is set to OFF.
In database column identity specification business chose is Identity Yes.
Somebody can tell what to do.
Can you make sure that in your EDMX model, your BusinessId is set to be handled by the database (property StoreGeneratedPattern = Identity)?? Also: why is your primary key nullable (long?) - makes no sense whatsoever. Your primary key must never be null !
BusinessId can not be empty/null since you have not specified that it should be autogenerated by Sql Server (which Identity means).
Since you are using Code First to generate your database, just change to:
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public long? BusinessId { get; set; }
override OnModelCreating in DbContext and add in it following Fluent API:
modelBuilder.Entity<Business>().HasRequired(m => m.Address).WithRequiredPrincipal(m => m.Business).WillCascadeOnDelete(true);

Resources