Показаны сообщения с ярлыком entity. Показать все сообщения
Показаны сообщения с ярлыком entity. Показать все сообщения

вторник, 11 января 2011 г.

Guid as PrimaryKey on Entity FrameWork


Hi, I am doing a little test with EF4, and I've tried to set up one entity which the primary key is one Guid,
Till this point, every thing is ok!, but whene try to insert into database, the visual studio throw one error saying that the object can't be saved because the Id (that´s my primary key) is null, otherwise the EF don't genarate one Guid for Id!
What can I do to solve my problem?
Is the GUID primary key column auto-generated at the database side?   Please set the StoreGeneratedPatterns to Identity on the GUID PK property.  For detail, please see http://blogs.msdn.com/alexj/archive/2009/05/20/tip-19-how-to-use-optimistic-concurrency-in-the-entity-framework.aspx &http://msdn.microsoft.com/en-us/library/dd283139.aspx. 

понедельник, 10 января 2011 г.

How to acquire the ID of last row inserted using Entity Framework?


Identity columns get its value after the entity is saved.
Given the following table:
CREATE TABLE T2 ( ID INTEGER PRIMARY KEY AUTOINCREMENT, Value TEXT)
The following code shows you the id for the inserted row:
using (TestEntities entities = new TestEntities())
{
    T2 t2 = new T2();
    t2.Value = "some value";
    entities.AddToT2(t2);
    entities.SaveChanges();

    Console.WriteLine(t2.ID);

}

четверг, 6 мая 2010 г.

Store update, insert, or delete statement affected an unexpected number of rows (0)



Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries.



This exception is letting you know that no rows were updated. There are several reasons why you may encounter this error.
One simple reason is that when attaching entities to an Object Context, you need to use the AddObject() method if the entity is newly created (and doesn't have an Entity Key), whereas you can use the Object Context Attach() method if the entity already exists and is being updated. Here is some code to demonstrate this (where "EntityContainerName" is the name of your Entity Framework container and "EntitySetName" is the name of the Entity Set to which you are adding the entity):
if (entity.EntityKey == null || entity.EntityKey.IsTemporary)
{
   this.ObjectContext.AddObject("EntityContainerName.EntitySetName", entity);
}
else
{
   this.ObjectContext.Attach(entity);
}

Note that you need to be careful when adding entities that are related to other entity objects because Object Services attempts to add the related objects too.

Инструкции по обновлению, вставке или удалению из хранилища затронули непредвиденное число строк (0)



Инструкции по обновлению, вставке или удалению из хранилища затронули непредвиденное число строк (0). Сущности могли быть изменены или удалены с момента их загрузки. Обновите записи диспетчера ObjectStateManager.



Это исключение говорит о том что не было обновлено не одной строки. В моем случае это произошло из-за того что я забыл добавить в таблицу поле Id. И Entity Framework просто не знала какие записи нужно обновить.

четверг, 1 апреля 2010 г.

ASP.NET Web sites That Have EDMX files do not compile and deploy in partial trust



After finishing one of the websites that were developed using Entity framework , I published  it to godaddy hosting. When i tried to open the newly published site, i got the following error:


Parser Error Message: Type 'System.Data.Entity.Design.AspNet.EntityDesignerBuildProvider' cannot be instantiated under a partially trusted security policy (AllowPartiallyTrustedCallersAttribute is not present on the target assembly).
After some investigation , I found that the mentioned error was caused by the following build Provider section that were placed in web.config by VS 2008:
<buildproviders>
<add extension=".edmx" type="System.Data.Entity.Design.AspNet.EntityDesignerBuildProvider"></add></buildproviders>
The “EntityDesignerBuildProvider” class is contained in  System.Data.Entity.Design.dll which does not have the AllowPartiallyTrustedCallersAttribute and so any call to it in the partial trust will fail.
when i removed the mentioned “buildProviders” section and refreshed the site, i got the following error:
The specified default EntityContainer name 'entity model name here' could not be found in the mapping and metadata information.
Parameter name: defaultContainerName.
After that i started to think that removing the mentioned section prevented the complier from compiling the entity model.
I think the problem is that since i didn’t precompiled the website and just copied it to the hosting server(using “copy website” option), the runtime will try to compile it dynamically (including the entity model “edmx" file) hence the first  mentioned error will occur.
many solutions comes to my head, like pre-compiling the website to avoid dynamic compilations on the hosting server, or just moving the entity model from App_code to a separate class library project which allow me to only build the class library project and publish the dll to the website Bin directory.
precompiling the website wasn’t an option for me because i know that i still need to apply partial updates to it and so i can’t re-upload the whole stuff every time i change something in the website.
So i selected the second solution.I goes a head and moved the entity model file “edmx” from the website App_Code  to a separate class library project.then compiled entity model project and added it’s resulted dll to the website Bin directory.
Problem solved :)
Hope that help you !

четверг, 25 марта 2010 г.

Foreign Key Relationships FAQ in the Entity Framework



We’re going to look at the designer experience, the EDMX model differences and a few coding examples. We’ll use this extremely simple database model:
Untitled
Note the fact that the Posts table has a foreign key to the Blogs table.
Designer Experience
Start by creating a new WPF application then add a new ADO.NET Entity Data Model item to it. Choose to generate the model from the database. Open the Tables portion of the treeview and check the Blogs and Posts tables. Note when choosing the tables with which to generate Entities “Include Foreign Key Columns in the Model” is checked by default. This means new models by default will use the new FK associations rather than Independent Associations. Independent Associations were previously the only type of association offered in the Entity Framework and still can be used. If you want just Independent Associations in your model, you’ll need to uncheck the Include FK Columns in the Model checkbox.
Untitled

After clicking Finish your model should look as follows:
Untitled
Double click the association and you’ll see the foreign key properties for the relationship:
Untitled
Let’s leave this as is for now but note it’s possible to switch an existing Association between an FK or Independent Association type. In this case if you wanted to switch an Association to be Independent, you’d press the Delete button in the Referential Constraint dialog. After doing so you’d need to map the Independent Association appropriately and remove the BlogID property from the Post Entity. For now let’s move on without changing the association type.
For comparison sake, add a new entity to the design surface from the toolbox. Once done, right click on the entity and choose Add->Association:
Untitled
Note that your association doesn’t have to be an FK association (association types can be mixed in the same model). Uncheck the ‘Add foreign key properties to the ‘Blog’ Entity’ check box then Click OK in the dialog. This will let us later look at the model differences between Independent and Foreign Key associations.
So far we’ve: created a WPF project, added an EDM Data Model to it, reverse engineered our Blogs and Posts tables to the model, then added a third entity and created an Independent Association with it.
XML model differences:
We’re going to briefly diverge and look at some of the differences in the XML generated for the different types of associations in our simple model. If you don’t want to do this, feel free to skip to the next section.
Right click on the EDMX file in your project and choose Open With->XML Editor. This will close the design surface and open the contents of the EDMX file in the XML Editor.
Scrolling down, the CSDL XML fragment for our Independent Association looks like this:
<Association Name="Entity1Blog">
<End Type="BlogsModel.Entity1" Role="Entity1" Multiplicity="1" />
<End Type="BlogsModel.Blog" Role="Blog" Multiplicity="*" />
Association>
It would also have an MSL XML fragment that tells EF how to traverse the relationship if we’d mapped the new entity & association to storage objects. Since we didn’t complete the mappings the fragment is missing.
The CSDL XML fragment for our FK Associations looks like this:

<Association Name="FK_BlogPost">
          <End Role="Blogs" Type="BlogsModel.Blog" Multiplicity="1" />
          <End Role="Posts" Type="BlogsModel.Post" Multiplicity="*" />
          <ReferentialConstraint>
            <Principal Role="Blogs">
              <PropertyRef Name="BlogID" />
            Principal>
            <Dependent Role="Posts">
              <PropertyRef Name="BlogID" />
            Dependent>
          ReferentialConstraint>
Association>
Notice the ReferentialConstraint element and its contents. There is also no MSL XML fragment for the relationship.
One other thing of interest to note is the Post EntityType has this fragment in the CSDL:
Having the BlogID property on the Post Entity will allow us to directly read & manipulate its value plus use it for data binding (no more need for partial classes with this exposed as a property).
This divergence this tells us three things:
  • EF is handling the two different types of Associations completely differently.
  • If you want to dig into an EDMX and tell what types of Associations you have you can (but looking at the XML can hurt your eyes J).
  • Foreign Key Associations add the parent ID key properties as properties on the child object. This is useful in a number of ways.
Coding experience
Double click on the EDMX file in your project. After clicking Yes, this should reopen the EF Designer for your model. Delete Entity1 from the design surface. This should give you valid model with everything mapped (exactly what you had after running the Add->New Item wizard).
We’re going to run through a few scenarios of how to code against our model. To facilitate, add a button to your WPF form and double click it.
Scenario 1: Adding new Blog and a new Post together by setting Navigation properties.
Note this is what you used to do without FK Associations and is still the recommended way of adding two newdependent objects together. We’ll talk about why in a few minutes. Inside the button event handler add the following code:
using (BlogsEntities ctx = new BlogsEntities())
{
    Blog myBlog = new Blog { BlogID = 9, Name = "Tim's blog", Owner = "Tim" };
    Post myPost = new Post { PostID = 102, Title = "Post Title", PostContent = "TestContent",
= DateTime.Now, ModifiedDate = DateTime.Now };
    //Nav properties will work immediately.
    myBlog.Posts.Add(myPost);
    ctx.Blogs.AddObject(myBlog);
    ctx.SaveChanges();
}
This code opens a connection to the DB, creates a new blog object, creates a new post object, adds the post object to the blog object’s Posts collection, adds the new blog objects to the context, then saves the changes to the database. Note that as soon as we added the myPost object to the Posts collection of myBlog we could use the navigation properties to traverse between the objects.
Scenario 2: Adding new Blog and a new Post together but set the Post BlogID FK property instead of adding to the myBlog Posts collection.
Delete the code you just placed in the event handler and replace it with the following:
using (BlogsEntities ctx = new BlogsEntities())
            {
                Blog myBlog = new Blog{BlogID = 11, Name = "Tim's blog", Owner = "Tim"};
                Post myPost = new Post{PostID = 101,Title = "Post Title", CreatedDate = DateTime.Now,  
                    ModifiedDate = DateTime.Now, PostContent="Post Content", BlogID = 11};
                ctx.Posts.AddObject(myPost);
                ctx.Blogs.AddObject (myBlog);
                ctx.SaveChanges();
            }
Note that the navigation properties on the two new objects won’t map to each other until after SaveChanges is called. This is because the context doesn’t know about the parent object yet.
Scenario 3: Adding a new post to an already existing blog.
Replace the code in the event handler with the following:
using (BlogsEntities ctx = new BlogsEntities())
            {
                Post myPost = new Post {PostID = 102, Title = "Post Title", CreatedDate = 
DateTime.Now, ModifiedDate =DateTime.Now, PostContent = "Post Content", BlogID = 11};
                //Nav properties will work immediately b/c the Blog object already exists
                ctx.Posts.AddObject(myPost);
                ctx.SaveChanges();
            }
Note we never loaded the Blog object into memory. We knew BlogID 11 was a valid ID and set the post.BlogID property directly. Note also, the navigation property for myPost.Blog will work immediately after setting the FK property because the Blog object already exists in the context. Being able to set the property directly enables some previously difficult data binding scenarios as well as can make some coding experiences easier.
These three coding examples show different ways of creating new objects and setting up their relationships using navigation properties and FK associations.
Summary


In .NET 4.0 we’ve added support for FK Properties and FK Associations to the Entity Framework. It’s still possible to use Independent Associations and the two can be mixed in models. We’re excited to offer FK Associations because they simplify many common Entity Framework coding tasks. Hopefully this walkthrough has given you a feel for how you can use FK Associations and Properties.

Model First Data Base generation in the Entity Framework 4.0



An exciting new Entity Framework Designer feature in Visual Studio 2010 is the ability to generate DDL that will create a database that can store your entity data model. This feature is not only exciting because it brings a long overdue capability to life, but because it is fully extensible: You can take control of the entire process, or plug into parts of it. For example, you can take over the DDL generation step to add support for your database of choice, or to customize the DDL generation process. Alternatively, you can take over the inheritance mapping step and replace our out-of-the box strategy (which is table-per-type) with your own. Or take over the entire mechanism and generate both stored procedure mappings and CRUD stored procedures for all your types. In a future post, we will show you exactly how to do this and provide an implementation of the table-per-hierarchy mapping for you to use or modify.
For now, let’s take a quick look at this feature by taking a very simple model:
clip_image002
We right click…and in the context menu we see, and click on, “Generate Database Script from Model”:
clip_image002[7]
The database generation wizard asks for a database to target. This information is used by the wizard to determine which database-specific types to translate the Entity Data Model (EDM) types to, and how to render DDL that is appropriate for the target database. In this case, I just created a new Microsoft SQL Server database file:
clip_image002[9]
Once we click on next, we are shown a preview of the generated DDL, which will be saved to disk once we click on “Finish”. Here is an excerpt from the DDL generated now for SQL Server:
…
-- Creating table 'IngredientSet_Protien'
CREATE TABLE [dbo].[IngredientSet_Protien] (
    [Cut] nvarchar(100)  NOT NULL,
    [Type] nvarchar(70)  NULL,
    [Id] int  NOT NULL
);
GO
-- Creating table 'IngredientSet_Plant'
CREATE TABLE [dbo].[IngredientSet_Plant] (
    [IsFruit] bit  NOT NULL,
    [IsHerb] bit  NOT NULL,
    [IsVegetable] bit  NOT NULL,
    [Id] int  NOT NULL
);
GO

-- --------------------------------------------------
-- Creating all Primary Key Constraints
-- --------------------------------------------------

-- Creating primary key on [Id] in table 'RecipeSet'
ALTER TABLE [dbo].[RecipeSet] WITH NOCHECK
ADD CONSTRAINT [PK_RecipeSet]
    PRIMARY KEY CLUSTERED ([Id] ASC)
    ON [PRIMARY]
GO
…
-- --------------------------------------------------
-- Creating all Foreign Key Constraints
-- --------------------------------------------------

-- Creating foreign key on [Chef_Id] in table 'RecipeSet'
ALTER TABLE [dbo].[RecipeSet] WITH NOCHECK
ADD CONSTRAINT [FK_ChefRecipe]
    FOREIGN KEY ([Chef_Id])
    REFERENCES [dbo].[ChefSet]
        ([Id])
    ON DELETE NO ACTION ON UPDATE NO ACTION
…
Note here that the default inheritance mapping strategy is to create a table for all subtypes: In the above DDL, you can see that we are generating tables for the Protien and Plant subtypes. These tables are named with the name of the EntitySet in which the types live, to which we append the name of the type itself.
Note also that we generate primary and foreign key constraints for the model.

Automatic Generation of Stored Procedure Return Types



A new feature of the Entity Framework in .NET 4.0 is the ability to return collections of complex type instances from stored procedures. In the next public release of the designer, we have enriched this functionality by adding the ability to automatically create these complex types by querying stored procedure metadata from the database server. To demonstrate this feature, we will use the Northwind database, and we will focus on a stored procedure called “CustOrdersDetail”. Looking at the designer’s model browser window after we reverse engineer Northwind, we see:
Untitled
Double-clicking “CustOrdersDetail” brings up the “Add Function Import” dialog:
Untitled
We click “Get Column Information” in order to see the metadata returned by the server about this stored procedure’s return columns. Then, we click on the “Create New Complex Type” button, and the designer automatically creates a new complex type that matches the shape of the data returned from the stored procedure:
Untitled
To make life more interesting (and realistic,) let’s rename some of the properties in the generated complex type: ProductName to Name, and UnitPrice to Price. To keep things running, we then need to fix the function import’s mappings to look like this:
Untitled
Finally, to simulate some real-world churn, we change the stored procedure’s return shape: We’ll rename “UnitPrice” to “UnitPricing”, add a new column called “Foo”, and delete “Quantity”:
ALTER PROCEDURE CustOrdersDetail @OrderID int
AS
SELECT ProductName,
    UnitPricing=ROUND(Od.UnitPrice, 2),
    Discount=CONVERT(int, Discount * 100),
       Foo = '!', 
    ExtendedPrice=ROUND(CONVERT(money, Quantity * (1 - Discount) * Od.UnitPrice), 2)
FROM Products P, [Order Details] Od
WHERE Od.ProductID = P.ProductID and Od.OrderID = @OrderID
That done, we double click on the function import again, get column information, and this time, click on the “Update” button. The designer will now inspect the mappings, the existing complex type, and the new return shape, and produce these proposed changes to the complex type:
Untitled
As you can see, “Foo” will be added, and “Quantity” will be deleted. In addition, the mappings are used to map “Name” to “ProductName” meaning no action will be taken for it. Finally, since “UnitPricing” is seen as new, “Price” will be deleted and “UnitPricing” will be put in its stead. Since we do not want this, we will rename the column in the function import’s mapping to “UnitPricing” and rerun the above process. This time we get:
Untitled
Which is what we would want.
In conclusion, the designer now exposes the Entity Framework’s new ability to return complex type instances from stored procedure. On top of this, it adds some features to make this capability easier to use and to iterate over.