Search code examples
breezenavigation-properties

Initilialize Navigation Property when creating new Entity with Breeze


I have simple Model defined as

public class Project
{
    public int Id { get; set; }

    public string Title { get; set; }

    public string Description { get; set; }

    public int StatusId { get; set; }

    public virtual Status Status { get; set; }
}

public class Status
{
    public int Id { get; set; }
    public string Name { get; set; }
}

So, currently If I try to create a new Project Entity with breeze, it initializes the navigation property "Status" with null. How can I initialize it with default value? Note that, I don't want any binding with drop down field for this field at least for create operation.

function createNewProject() {
     return manager.createEntity('Project');
}

Solution

  • You can define a custom constructor for the Project entity type and set a default StatusId value in there. The Status navigation property will be set to the relevant status entity (assuming the entity is in the breeze cache). For example:

    function Project() {
        this.StatusId = desiredDefaultStatusEntityId;
    }
    
    var manager = new breeze.EntityManager('...');
    manager.metadataStore.registerEntityTypeCtor('Project', Project);
    

    Take a look at Extending entities for some more information on extending entities.