Entity FrameWork - Exception on SaveChanges - entity-framework

I have this code saving a simple Entity:
ExecutionEngineEntities db = new ExecutionEngineEntities();
Task task = new Task();
task.Message = "Test";
task.Result = "Test";
task.Name = "Test";
db.Tasks.AddObject(task);
db.SaveChanges();
This is the exception:
A first chance exception of type 'System.Data.UpdateException' occurred in System.Data.Entity.dll
Unable to update the EntitySet 'Tasks' because it has a DefiningQuery and no <InsertFunction> element exists in the <ModificationFunctionMapping> element to support the current operation.
The program '[6092] WebDev.WebServer40.EXE: Managed (v4.0.30319)' has exited with code 0 (0x0).
This is the create table code:
CREATE TABLE [dbo].[Tasks](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [nchar](50) NULL,
[Message] [nchar](1000) NULL,
[Result] [nchar](1000) NULL
) ON [PRIMARY]
After searching in google I found that mode people who got this error has a relation problems, this is not my case
Thanks

Maybe the answer here can help you: It has a DefiningQuery but no InsertFunction element... err
It could be that in the EF model it is configured that this entity is a view and not a table. Views don't support create, update or delete operations, so you can't insert.

Related

Get Record ID in Entity Framework 5 after insert

I realize this must be a relatively simple thing to do, but I'm not getting what I'm looking for with Google.
I need to get the record ID of the record I just saved using the Entity Framework. With SQL queries we used "Select ##IDENTITY as 'Identity';"
If anyone can help it would be greatly appreciated.
The default behavior of Entity Framework is it sets identity fields on entities from the database right after SaveChanges is called.
In the following sample code, before SaveChanges is called, my employee has a default ID of 0. After SaveChanges my employee has a generated ID of 1.
using (TestDbEntities context = new TestDbEntities())
{
Employee e = new Employee ();
e.FirstName = "John";
e.LastName = "Doe";
context.Employee.Add(e);
context.SaveChanges();
Console.WriteLine("Generated ID: {0}", e.ID);
Console.ReadKey();
}

Sybase ASE Entity Framework - Error while updateing record to database -"incorrect syntax near '('.\n"

I am trying to simple update and existing record. And I am getting the error - incorrect syntax near '('.\n
Entities db = new Entities();
try
{
var existingObj = new OBJETE
{
OB_ID_MR = 348,
OB_ID_JE = 1156,
OB_IS_NT = false,
OB_ID_MS = 88,
OB_POSITIONABS = "12,12,12,12",
OB_ORDRE = 1,
OB_UPDATEDATE = DateTime.Now
};
db.OBJETEs.Attach(existingObj);
db.ObjectStateManager.ChangeObjectState(existingObj, System.Data.EntityState.Modified);
db.SaveChanges();
If I try to update "not null" columns then I can update the records in this table. But when I try to update nullable values then I am getting this error consistently. Please advice.
Found it! My Table did not have a Primary Key. Entity Framework add some addition tag to disable update of such tables.
So either you add a primary key to the table or if that is not an option like in my case the work around is to open the edmx file in Text mode, and remove the entry for the tag - "DefiningQuery" and all its contents for the Table in question. Additionally we need to change => store:Schema="dbo" to Schema="dbo" for that Table. This should fix the issue.

Entity Framework with POCO Template and FKs in Model - Null Ref Exception

I'm using Entity Framework 4 with the POCO code generation template from Microsoft downloaded from the Visual Studio gallery. I am also leaving the default option to "Include foreign keys in model" selected when generating the EF model from the database.
I've been able to reproduce this problem with a very simple model, only two tables/classes in an optional one-to-many relationship. In this case, I'm using an Address and a Person. A Person can have one or zero addresses, and an Address can have zero to many People.
The tables look like this:
CREATE TABLE [dbo].[Person](
[PersonID] [uniqueidentifier] NOT NULL,
[FirstName] [nvarchar](50) NULL,
[LastName] [nvarchar](50) NULL,
[AddressID] [uniqueidentifier] NULL,
CONSTRAINT [PK_Person] PRIMARY KEY CLUSTERED ([PersonID] ASC )
CREATE TABLE [dbo].[Address](
[AddressID] [uniqueidentifier] NOT NULL,
[Street1] [nvarchar](50) NOT NULL,
[Street2] [nvarchar](50) NULL,
[City] [nvarchar](50) NOT NULL,
[State] [char](2) NOT NULL,
[Country] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_Address] PRIMARY KEY CLUSTERED ([AddressID] ASC)
ALTER TABLE [dbo].[Person] WITH CHECK ADD CONSTRAINT [FK_Person_Address]
FOREIGN KEY([AddressID])
REFERENCES [dbo].[Address] ([AddressID])
When I try to create an Address object and add it to an existing Person object pulled from the database, I get a null reference exception:
TestPOCOEntities ctx = new TestPOCOEntities();
var person = ctx.People.FirstOrDefault(p => p.PersonID == new Guid("58AD37B4-1EBE-4649-940C-A141732C9901"));
var addr = new Address {AddressID = Guid.NewGuid(), Street1 = "123 Main St"};
person.Address = addr; // This line throws the exception
ctx.SaveChanges();
Digging into the call stack, the exception isn't being thrown from my code, or even the template-generated code, but inside the runtime dynamic proxy for the Person class in the AddressID setter. (Specifically, the System.Data.Objects.EntityEntry.FixupEntityReferenceByForeignKey(EntityReference reference) method.)
This exception does not occur if I use the default EF code generation instead of the POCO template. It also does not occur if I use the POCO template but uncheck the "Include foreign keys in model" checkbox when generating the model from the database.
I can get the error to go away if I add the following:
var addr = new Address {AddressID = Guid.NewGuid(), Street1 = "123 Main St"};
ctx.Addresses.AddObject(addr); // Adding this line...
person.Address = addr; // Means no more exception here!
I don't see why the combination of using the POCO template and including foreign keys in the model should require this kind of code change when interacting with my persistent objects. Is this a known bug? Am I missing something? Is this by design for some reason?
this is a potential bug of EF, usually then refresh a created entity (resave changes with new data) solution:
http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/832af255-d1c2-41d5-9e95-9cdf3b15bb57
the cheat is add the entity to the collection context first
second assign to the father entity
third, savechanges normally!
enjoy

EF 4.0 Entity does not pick up new values after insert (select entity after insert)

I am using Entity Framework 4.0 POCO entity
I have mapped custom stored procedure on insert
PROCEDURE [dbo].[usp_MyTable_Insert]
(
#Value1 char(1),
#Value2 varchar(5),
#Value3 varchar(20)
....
)
AS
BEGIN TRANSACTION
INSERT INTO "dbo"."MyTable"
(
"Value1",
"Value2",
"Value3"
)
VALUES
(
#Value1,
#Value2,
#Value3
)
DECLARE #Id int
--Get the latest Id.
SET #Id = ( SELECT CAST(##IDENTITY AS INT) )
--update the table with the some values
UPDATE "dbo"."MyTable"
SET Value3 = ( SELECT SomeTableColumn
FROM SomeTable
WHERE Something = Something
)
WHERE [Id] = #Id
COMMIT TRANSACTION
SELECT #Id AS "Id"
END
It is inserting entity into database and then updating some of the columns in database
then returning identity. All pretty simple.
public int InsertRecord(RecEntity recEntity)
{
context.AddObject("RecEntities", recEntity);
context.SaveChanges();
return recEntity.Id;
}
Method insert working well.
Then i need to update current entity with values which stored procedure inserted.
I have method in my repository to retrieve data
public RecEntity SingleRecEntity(Expression> where)
{
return context.RecEntities.Single(where);
}
When i am calling this method values values inserted by stored procedure doesn't come to entity.
id = repository.InsertRecord(recEntity);
recEntity = repository.SingleBrokerPreRegistration(x => x.Id == id); // new values didnt come here from database
I run the query generated by entity framework in query analyzer, it is returning all up to date values.
But fore some reason datacontext don't want to update this entity.
Probably there is should be some ways to change this.
May be some one may explain this behaviour.
Need help.
Try the Refresh method with the StoreWins parameter.
EF does not refresh the values in case there is already an attached object with Entity Key specified unless the Refresh method is not called explicitly
If you run .Load(Objects.MergeOption.OverwriteChanges) on the collection you'll get any newly added items. If you want the deleted items to be "refreshed" you'll need to detach the entities from the collection before running .Load
Putting it all together (sorry about the vb)
For Each child in Parent.ChildCollection.ToArray()
context.Detatch(child)
Next
Parent.ChildCollection.Load(Objects.MergeOption.OverwriteChanges)
This works for me, but if there's a more elegant way I'd love to see it!

Entity Frmwk pb: search for 'added' entities in current context

I'm using guids as PK for my entities.
As EF doesn't support the newid() SQL statement, I force a Guid.NewGuid() in my creation methods.
Here is my problem :
I've a table with a clustered unique constraint (2 strings, not PK).
I'm running some code in the same EF context which perfoms operations and adds/links entities, etc.
Is it possible to search for an entity in 'Added' state in my context ? ; that is to say which is in my context, but not yet inserted in my DB.
To avoid the raising of the SQL unique constraint, I have to know if the entity is already 'queued' in the context, and to re-use it instead of creating a new Guid (... and a different entity! :( )
this post saved me :) :
Link
var stateEntries = context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EtityState.Modified | EntityState.Unchanged);
var roleEntityEntries = stateEntries.Select(s => s.Entity).OfType<Role>();
roleEntity = roleEntityEntries.FirstOrDefault(r => r.RoleName.Trim().ToLower() == roleName.Trim().ToLower());
if (roleEntity == null)
{
return new Role { RoleName = roleName };
}