how to update model after droping coulmn from sql database - sql-server

I droped catalog_filename coulmn from database and I see this error :
Schema specified is not valid. Errors:
The relationship 'J_DBModel.FK__CATALOG_T__CATEG__41B8C09B' was not loaded because the type 'J_DBModel.CATALOG_TBL' is not available.
The following information may be useful in resolving the previous error:
The required property 'CATALOG_FILENAME' does not exist on the type 'Javad_New.Models.CATALOG_TBL'.
In my model catalog_filename is still existed .
public long CATALOG_ID { get; set; }
public Nullable<long> CATEGORY_FK { get; set; }
public string CATALOG_TITLE { get; set; }
public string CATALOG_DESC { get; set; }
public string CATALOG_CATEGORY { get; set; }
public Nullable<int> CATALOG_PAGENO { get; set; }
public Nullable<bool> CATALOG_RTL_FLAG { get; set; }
public string CATALOG_FILENAME { get; set; }
public Nullable<System.DateTime> CATALOG_DATE { get; set; }
public virtual CATEGORY_TBL CATEGORY_TBL { get; set; }

In code first pattern never (delete / change) in sql.
you should manage things from migration
in your case, just add column to table from sql then delete from c# class and add new migration

Make changes to the database
The first step is to make the necessary changes to your database. In this example, the only change being made is to a column name. Simple enough. It is important to note that if you have any stored procedures, etc, that rely on that column name, those should be updated as well.
Open the .edmx file
The model exists in your project as an .edmx file. Open the Solution Explorer (ctrl + alt + L) and type .edmx into the search bar at the top. Your model should appear (it’s the only one with that extension). Open it up and you will see a diagram of connected tables.
Delete the old table from the model
Before updating the model, it is necessary to delete the existing version of the table(s) you changed from the model. In the .edmx, right-click in the area between tables and select Model Browser. It will open a file tree of all the tables contained in your model. Delete every instance of the table you changed in your database. I find it helpful to enter the name of the modified table in the search bar at the top of the model browser, which will show you all tables in the model with that name. Delete them! Note that attempting to Update Model from Database without deleting the old tables first will not truly update the model, and your app may not compile correctly.
Update Model from Database
Now that your old table is deleted, right-click in the .edmx and select Update Model From Database. You will see the following screen:

Related

Workflow for EF Core with Database Project

Feel free to tell me that this question needs to be moved and I will move it. I just don't know where else to go for help.
My current work flow is:
Create the database first (database Actual)
Run scaffold command which creates my models
Create a Visual Studio Database project
Import the database (database project)
Whenever I need to make a change to the database I follow the below:
Change the database project
Run a Schema Compare
Verify and update the database Actual
rerun the scaffold command with a -Force to rebuild all the models.
What (if any) type of problems am I leaving myself open to down the road?
I am not seeing the value of database migrations as I am updating the database first but using the database project to provide source control and some protection.
I always used to use the graphic database tool, but obviously with Core that is no longer an option.
I have also considered Devart's Entity Developer as a ORM.
Your thoughts and feedback are VERY much appreciated.
So the biggest problem is what happens when I need to make changes to the model.
So something simple like:
public partial class UserInfo
{
public int Id { get; set; }
[Required]
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public DateTime RecordCreated { get; set; }
}
My '[Required]' will obliviously be gone after a -force.
Joe
That is the correct "database first" workflow for EF Core, and you would not use migrations in that scenario. Be sure to place customizations to your entities or DbContext in separate partial class files so they don't get clobbered when you regenerate the entities.
always used to use the graphic database tool, but obviously with Core that is no longer an option.
With this workflow you can use any graphical design tool you want for your database schema.

Why am I getting DbUpdateException: OptimisticConcurrencyException?

I have a Category class:
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
}
I also have a Subcategory class:
public class Subcategory
{
public int SubcategoryId { get; set; }
public Category Category { get; set; }
public string SubcategoryName { get; set; }
}
And a Flavor class:
public class Flavor
{
public int FlavorId { get; set; }
public Subcategory Subcategory { get; set; }
public string FlavorName { get; set; }
}
Then I also have Filling and Frosting classes just like the Flavor class that also have Category and Subcategory navigation properties.
I have a Product class that has a Flavor navigation property.
An OrderItem class represents each row in an order:
public class OrderItem
{
public int OrderItemId { get; set; }
public string OrderNo { get; set; }
public Product Product { get; set; }
public Frosting Frosting { get; set; }
public Filling Filling { get; set; }
public int Quantity { get; set; }
}
I'm having issues when trying to save an OrderItem object. I keep getting DbUpdateException: An error occurred while saving entities that do not expose foreign key properties for their relationships. with the Inner Exception being OptimisticConcurrencyException: Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. I've stepped through my code several times and I can't find anything that modifies or deletes any entities loaded from the database. I've been able to save the OrderItem, but it creates duplicate entries of Product, Flavor, Subcategory and Category items in the DB. I changed the EntityState of the OrderItem to Modified, but that throws the above exception. I thought it might have been the fact that I have Product, Frosting and Filling objects all referencing the same Subcategory and Category objects, so I tried Detaching Frosting and Filling, saving, attaching, changing OrderItem entity state to Modified and saving again, but that also throws the above exception.
The following statement creates duplicates in the database:
db.OrderItems.Add(orderItem);
Adding any of the following statements after the above line all cause db.SaveChanges(); to throw the mentioned exception (both Modified and Detached states):
db.Entry(item).State = EntityState.Modified;
db.Entry(item.Product.Flavor.Subcategory.Category).State = EntityState.Modified;
db.Entry(item.Product.Flavor.Subcategory).State = EntityState.Modified;
db.Entry(item.Product.Flavor).State = EntityState.Modified;
db.Entry(item.Product).State = EntityState.Modified;
Can someone please give me some insight? Are my classes badly designed?
The first thing to check would be how the entity relationships are mapped. Generally the navigation properties should be marked as virtual to ensure EF can proxy them. One other optimization is that if the entities reference SubCategory then since SubCats reference a Category, those entities do not need both. You would only need both if sub categories are optional. Having both won't necessarily cause issues, but it can lead to scenarios where a Frosting's Category does not match the category of the Frosting's SubCategory. (Seen more than enough bugs like this depending on whether the code went frosting.CategoryId vs. frosting.SubCategory.CategoryId) Your Flavor definition seemed to only use SubCategory which is good, just something to be cautious of.
The error detail seems to point at EF knowing about the entities but not being told about their relationships. You'll want to ensure that you have mapping details to tell EF about how Frosting and SubCategory are related. EF can deduce some of these automatically but my preference is always to be explicit. (I hate surprises!)
public class FrostingConfiguration : EntityTypeConfiguration<Frosting>
{
public FlavorConfiguration()
{
ToTable("Flavors");
HasKey(x => x.FlavorId)
.Property(x => x.FlavorId)
.HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasRequired(x => x.SubCategory)
.WithMany()
.Map(x => x.MapKey("SubCategoryId");
}
}
Given your Flavor entity didn't appear to have a property for the SubCategoryId, it helps to tell EF about it. EF may be able to deduce this, but with IDs and the automatic naming conventions it looks for, I don't bother trying to remember what works automagically.
Now if this is EF Core, you can replace the .Map() statement with:
.ForeignKey("SubCategoryId");
which will set up a shadow property for the FK.
If SubCats are optional, then replace HasRequired with HasOptional. The WithMany() just denotes that while a Flavor references a sub category, SubCategory does not maintain a list of flavours.
The next point of caution is passing entities outside of the scope of the DBContext that they were loaded. While EF does support detaching entities from one context and reattaching them to another, I would argue that this practice is almost always far more trouble than it is worth. Mapping entities to POCO ViewModels/DTOs, then loading them on demand again when performing updates is simpler, and less error-prone then attempting to reattach them. Data state may have changed between the time they were initially loaded and when you go to re-attach them, so fail-safe code needs to handle that scenario anyways. It also saves the hassle of messing around with modified state in the entity sets. While it may seem efficient to not load the entities a second time, by adopting view models you can optimize reads far more efficiently by only pulling back and transporting the meaningful data rather than entire entity graphs. (Systems generally read far more than they update) Even for update-heavy operations you can utilize bounded contexts to represent large tables as smaller, simple entities to load and update a few key fields more efficiently.

Creating seed model from data already in DB

Is there a way to convert data in an existing database into objects that can easily be put into a seed method?
Essentially I'd like to let some people add lines to my DB via a form and then convert that into an object that I can re-seed the DB anytime I need to make changes.
The database itself is created via code-first using the following model:
public class Combo
{
public int Id { get; set; }
public string MainPrefix { get; set; }
public string MainDescriptor { get; set; }
public string MainDish { get; set; }
public string Connector { get; set; }
public string SecondaryDescriptor { get; set; }
public string SecondaryDish { get; set; }
}
High level untested idea:
Create a new T4 template which will use either your context or direct SQL to query database and generate either C# static class with method (which will return collection of object created from database data) or SQL insert commands. Depending on what you choose you will either call static method in Seed to get all entities you want to insert or simply load the created SQL script and execute it.
You can also do the same without T4 by using Code Dom (if you want to generate C# code) and creating a new custom tool for visual studio.
These features can be part of your project or the result (C# code) can be compiled in separate external assembly.

Why can't SQL Server handle cascading deletes for two foreign keys pointing to the same table?

I'm using Entity Framework - Code First, and I've run into an issue where I have to disable cascading deletes for a particular foreign key.
Here is my entity class:
public class ChallengeMatch
{
public int Id { get; set; }
public int ChallengerClubMemberId { get; set; }
public int ChallengeeClubMemberId { get; set; }
public bool ChallengerWon { get; set; }
public string Score { get; set; }
public virtual ClubMember ChallengerClubMember { get; set; }
public virtual ClubMember ChallengeeClubMember { get; set; }
}
If I allow Code First to generate the database for this table with all default settings (which includes cascading deletes), it will throw an exception when it tries to generate the database objects.
If I add the following code to my DbContext class, I no longer get an exception, but now cascading deletes will only somewhat work:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<ChallengeMatch>()
.HasRequired(cm => cm.ChallengeeClubMember)
.WithMany()
.HasForeignKey(cm => cm.ChallengeeClubMemberId)
.WillCascadeOnDelete(false);
}
Because of this, I have to write code by hand. Specifically, if I'm about to delete ClubMember 13, I have to delete any ChallengeMatch whose ChallengeeClubMemberId is 13.
What I don't understand is why any of this should be necessary. Why can't SQL Server handle a cascading delete even if there are two foreign keys pointing to the same table? I can't think of any reason why this would fail.
It should be a simple three-step process (psuedo code):
Delete all challenge matches where ChallengerClubMemberId == 13
Delete all challenge matches where ChallengeeClubMemberId == 13
Delete the club member where Id = 13.
Why can't SQL Server do this or why does it choose not to?
The problem is that your configuration allows multiple cascade delete paths. This can happen if both your properties will point to the same ClubMember. SQL Server doesn't allow that. It is more about internal implementation of SQL server and more details can be found in this answer. I think that this check is simple and safe solution to avoid some race conditions during deletes cascading in parallel.

Coming from a relational database background, how should I model relationships in db4o (or any object database)?

I'm experimenting with db4o as a data store, so to get to grips with it I thought I'd build myself a simple issue tracking web application (in ASP.NET MVC). I've found db4o to be excellent in terms of rapid development, especially for small apps like this, and it also negates the need for an ORM.
However, having come from a SQL Server/MySQL background I'm a little unsure of how I should be structuring my objects when it comes to relationships (or perhaps I just don't properly understand the way object databases work).
Here's my simple example: I have just two model classes, Issue and Person.
public class Issue
{
public string ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime? SubmittedOn { get; set; }
public DateTime? ResolvedOn { get; set; }
public Person AssignedBy { get; set; }
public Person AssignedTo { get; set; }
}
public class Person
{
public string ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
The ID properties are just GUID strings generated by the .NET Guid.NewGuid() helper.
So here's how I initially thought the application would work; please ignore any security concerns etc and assume we already have a few Person objects stored in the database:
User logs in. Query the database for the Person which matches the username and password, and store his/her GUID id as a session variable. Redirect to app home screen.
Logged in user creates a new issue ticket, selecting the user to assign it to from a drop-down list. They fill in the other details (Title, Description etc), and then submit the form.
Query the Person objects in the database (by their GUID ID's) to get an object representing the logged in user and one representing the user the ticket has been assigned to. Create a new Person object (populated with the posted form data), assign the Person objects to the Issue object's AssignedBy and AssignedTo properties, and store it.
This would mean I have two Person objects stored against each Issue record. But what happens if I update the original Person—do all the stored references to that Person in the various issue objects update, or do I have to handle that manually? Are they references, or copies?
Would it be better/more efficient to just store a GUID string for the AssignedBy and AssignedTo fields (as below) and then look up the original person based on that each time?
public class Issue
{
public string ID { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public DateTime? SubmittedOn { get; set; }
public DateTime? ResolvedOn { get; set; }
public string AssignedByID { get; set; }
public string AssignedToID { get; set; }
}
I think I'm just stuck in a certain way of thinking which is confusing me. If someone could explain it clearly that would be most helpful!
Object-Databases try to provide the same semantics as objects in memory. The rule of thumb is: It works like objects in memory. Object databases store references between the objects in the database. When you update the object, that object is updates. And if you have a reference to that objects, you see the changed version.
In your case, the Issue-objects refer to the person object. When you update that person, all Issues which refer to it 'see' that update.
Of course, primitive types like int, strings, longs etc are handled like value objects and not a reference objects. Also arrays are handled like value objects in db4o, this means a array is stored together with the object and not as a reference. Everything else is stored as a reference, even collections like List or Dictionaries.
Please take a look at:
http://developer.db4o.com/Documentation/Reference/db4o-7.4/java/reference/html/reference/basic_concepts/database_models/object-relational_how_to.html
Best!

Resources