I am using Entity-Framework Database First , I have my ObjectContext.Entity bound to a binding source which in turn is bound to my winforms controls. When I change text on my winforms controls it populates down to Current ObjectContext.Entity - I click CreateCopy - to copy the current ObjectContext.Entity , now when I try to Add the new object - it fails, I tried simply to add the current object and it failed with the duplicate key error (of course), if I set the Key (it is ID type int, auto increment) to 0 it does not add it to the ObjextContext.EntitySet , so I said ok I will just save changes as well and see what happens - but it is not in the context so how can it save it ?? Neither does it save it. So what could I be doing wrong.
This is my CreateCopy Code
BrandItem = new BRAND();
BrandItem = TestBrand(BrandItem);// just a test case BrandItem ID, Name Columns
this.ContextEntities.BRAND.AddObject(BrandItem); // It is not adding anything here but I sure would like it to;
I have also tried
BrandItem = (ObjectContext.BRAND)bsBrand.Current; // This fails with a non-unique key error , if I change the ID to 0 it still does not work
Does any one know how to do this with an AutoIncrementing ID key and Entity Framework Database First ??
Related
This is C# and EF6. I have a function that sometimes runs twice (by design). As part of that function I'd like to check if a new object is the same as the newest entry in the DB and was created within the past 3 seconds. The main problem is that the Id column is auto-filled when the item is fetched, and EF6 won't let me clear it or set it to a standard number since it's the key property.
I think I can figure out the logic to check the time, but what would be the correct way to check if the two items are otherwise the same?
i want to set a property value in a table to default auto increment,but their are no options to do so in lightswitch2012 to my knowledge which is given that i recently started learning lightswitch,very light.
ok heres the real problem,this is the table
[customer][id,customer_id,name]
i want to set customer_id by default to id unless it is manually changed to different value.
how to acheive this?
In the Entity designer make your Customer_ID not required.
Write Code for Customers_Inserted.
Then, check to see if the Customer_ID is null. If it is, copy the ID field to it.
private void Customers_Inserted(Customer entity)
{
if (entity.Customer_ID == null) {
entity.Customer_ID = entity.ID;
}
}
You're right, there is no "auto-increment" data type available in LightSwitch. The ID property auto-increments, but that's a special case, handled by LightSwitch.
If you were attaching to an external SQL database, if you added a column that was an Integer Identity column, although it'll just appear as an Integer property in LightSwitch, it would still auto-increment because that's actually done in the SQL database itself.
The problem with all auto-increment properties is that you won't get the actual value until the record is saved.
Can I ask why you need an auto-increment property?
I may be misunderstanding what you are trying to achieve, but if you are using either a table or a grid, and you want to set the values for various entities for each new row your user adds (like customer_id = id, etc.), you can use the _Changed method and Add event to programmatically set any of the new row entities.
If this is along the lines of what you're looking for, watch Beth Massi's video How Do I: Copy Data from One Row into a New Row? You should be able to adapt her code to accomplish what you have in mind I think.
Sheesh...
I think this can be done but I just can't figure it out at the moment.
So I've created this app, that's working fine. But for some reason (too long to explain sorry) I would need to predict next ID to come from data table.
Note that last id + 1 will not work. I've tried this.
var lastProperty = db.Properties.OrderByDescending(p => p.PropertyID).FirstOrDefault();
int propID;
if (lastProperty == null)
{
propID = 1;
}
else
{
propID = 1 + lastProperty.PropertyID;
}
And as long as properties don't get deleted it works...
As soon as one is deleted, it messes up of course, since lets say we delete 6th Property,
last one will be 5th now, and with that code we'll get 6 5(last one) + 1, and I save my model related to Property with PropertyID 6 which I got from that code, and next Property will be 7 since database still remembers that 6 existed and was deleted... Model I intended to have same PropertyID as THAT last Property will not have it, and it'll fail...
Also, I can't add this AFTER saving Property, I realize that might seem as a solution but it's not. It has to be predicted.
Thank you... Please help...
UPDATE
This is the use case I'm trying to accomplish.
Property model with ID Name DataType properties.
List model with ID ListValue PropertyID properties.
When new Property is created user types in the Name, and from premade dropdown list for DataType selects a value, if that value is List, it opens additional form that contains a listbox, textbox and a button (add_Button). User types in the value in a textbox, and clicks the add_Button to add it to List.
Listbox is populated from List model, and add_Button, saves values from textbox to ListValue property of List, also as you've seen, I'm trying to manually add PropertyID to List by predicting it's value...
Then, upon finishing adding all the elements wanted through textbox, by clicking Create button, Property is then saved.
Hope this was clear enough.
It seems like you want to know the current state of the identity column:
SELECT IDENT_CURRENT('Table')
When need to know what your primary key values are going to be before committing to the Db you could use a uniqueidentifier (GUID) as the Pk for your Property and therefore as the Fk for your List entity. That way you can create it your self and it'll always be unique on committal.
You mention Entity Framework, have you tried adjusting your model?
StoreGeneratedPattern can be adjusted to allow automatic update of your local model when you store to the database.
I’m using Silverlight4 and Ria Service :
Imaging we have a table (called "MyTable") with 3 records ( 1 , 2 , 3 ) , I’ve just written the following codes somewhere in my application:
CurrentItem = 1;
MyContext.MyTables.Delete(CurrentItem);
CurrentItem = 2;
MyContext.MyTables.Delete(CurrentItem);
For some reasons, before hitting The “Save” Button, I want to reject the first deleted item(1) but still want to delete the second one(2) .it means that I can’t use :
MyContext.RejectChanges()
Because It will reject all changes (including the deleted item which what I do want to delete it) so I though, using IRevertibleChangeTracking can solve my issue .Something like this :
((IRevertibleChangeTracking) MyItem).RejectChanges();
But before using this Interface, I have to access the deleted Item. At first, It tried to get it via MyContext.MyTables but it doesn’t contain deleted records so I tried to obtain it by EntityChangeSet:
EntityChangeSet Changes = MyContext.EntityContainer.GetChanges();
MyTable DeletedItem = Changes.First<MyTables>( e => e.ID = 1 ) ;
And then I used IRevertibleChangeTracking:
((IRevertibleChangeTracking) DeletedItem ).RejectChanges();
But after Running, This line of code didn’t change the state of the record and it was kept as “Deleted” so by hitting the “Save” Button, It was deleted from the Database Physically !!!!
It seems IRevertibleChangeTracking doesn’t work for deleted/Added items ( it just works for modifed Items ).
So ,Is there any way to reject a particular deleted item from the DomainContext.
Thanks,
After a bit more hunting, I found where Colin Blair says:
Every RIA Services entity implements the IRevertibleChangeTracking interface. All you have to do is cast your entity to IRevertibleChangeTracking and call RejectChanges. RejectChanges does not work for new or deleted entities.
Instead of deleting each entity, can you set a boolean property to false, and when finished, delete the entities with the flag set to false?
I have an application which consists of simple schema of DB:
Networks 1-->* Shops
i use entityframework (Default EntityObject Code Generator) with winforms,
i use DataBinding to a grid to CUD these entities,
i have :
DbObjectModelContainer _context = new DbObjectModelContainer();
_context.ContextOptions.LazyLoadingEnabled = true;
NetworkBindingSource.DataSource = _context.Networks;
ShopsBindingSource.DataSource = NetworkBindingSource;
ShopsBindingSource.DataMember = "Shops";
NetworkBindingNavigator.BindingSource = NetworkBindingSource;
ShopBindingNavigator.BindingSource = ShopsBindingSource;
NetworkDataGridView.DataSource = NetworkBindingSource;
ShopDataGridView.DataSource = ShopsBindingSource;
all databinding is working good and synchronized, i can CUD on both grids on the Form and go to _context.SaveChanges() with no problem.
First Scenario
a simple scenario of Pressing "+"(add) on the NetworkBindingNavigator and right afterwards "X"(delete) on this empty line on the grid and finally i go to context.SaveChanges()
succeed without a problem.
Second Scenario
when i press "+"(add) on the ShopBindingNavigatorand then right afterwards i press "X"(delete) on this empty line on the grid and finally i go to _context.SaveChanges() i get :
System.Data.UpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Cannot insert the value NULL into column 'Location', table 'MyDB.dbo.Shops'; column does not allow nulls
my question is why didnt it happen in the first scenario as well (i dont allow NULL in Networks table as well) ?
Thanks.
Cannot insert the value NULL into column 'Location', table 'MyDB.dbo.Shops'; column does not allow nulls means you table does not accept NULL.
so can you check in the table if the column is nullable or not. If it is not nullable then when you say it has succeeded in your first scenario have a look at you DB. Somehow you must be inputting some default values into the tables.