2
votes

Im using Breeze in my ASP.NET WebAPI Project, I have added the breezecontroller

    [BreezeController]    
    public class BreezeController : ApiController
    {
        readonly EFContextProvider<MyEntities> _context 
            = new EFContextProvider<MyEntities>();

        [HttpGet]
        public string Metadata()
        {
           return _context.Metadata();
        }

unfortunately when I call createEntity I get the error Cannot attach an object to an EntityManager without first setting its key or setting its entityType 'AutoGeneratedKeyType' property to something other than 'None'

Isn't breeze auto intialized the entity when the metadata api was called?

TIA

2

2 Answers

7
votes

I'm betting that the entity you are trying to create is defined such that the client ... not the server ... is responsible for setting a unique key. I'll bet that the key property is a Guid because EF Code First assumes Guid key properties are determined by the client by default.

If so, then it is up to you to set the key when you create the entity BEFORE adding the new entity to the manager.

You have elected to create the new entity with the EntityManager.createEntity method. That's my favorite too.

But you must remember that this method tries to add the new entity to the manager for you automatically (as explained here). Therefore, to use this method, you must initialize the key to the new entity before Breeze adds it to the manager. You can do that in one of three ways:

  1. in a custom constructor that you've defined and registered with the type
  2. in a custom initializer that you've defined and registered with the type (see "Extending Entities" documentation page for both techniques)
  3. in the initializer parameter to the createEntity call.

Option #3 looks like this:

var newThing = manager.createEntity("Thing", {id: breeze.core.getUuid()});

I would pick option #1 myself.

2
votes

Please post your client side breeze code. Without it I can't tell for sure, but I would guess that you have not fetched the metadata for that entity before your "createEntity" call. You must have the metadataStore before you can create an entity. For example:

breezeProjectManager().metadataStore.fetchMetadata().then(function() {
  //createEntity code here 
}