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)
Related
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?
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
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...
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; }
}
When I build my model to be returned by WCF RIA Services to silverlight, the list properties are not shown in the silverlight client.
Class:
public class Batch
{
[DataMember]
public DateTime Time { get; set; }
[DataMember]
public List<BasicInfoModel> Accepted { get; set; }
[DataMember]
public List<BasicInfoModel> UnAccepted { get; set; }
}
public class Batch
{
[Key]
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
}
When in the client, it seems the Lists are not generated, for example, this is my loaded callback event:
private void Callback(LoadOperation<Batch> loadOperation)
{
//there is no such property as `Accepted`
var acceptedList = loadOperation.Entities.FirstOrDefault().Accepted;
}
Am I doing something wrong?
I suppose, you've missed DataContract attribute, e.g.
[DataContract]
public class Batch
{
[DataMember]
public DateTime Time { get; set; }
[DataMember]
public List<BasicInfoModel> Accepted { get; set; }
[DataMember]
public List<BasicInfoModel> UnAccepted { get; set; }
}
http://msdn.microsoft.com/en-us/library/ms733127.aspx