2014-02-07 50 views
0

我的數據庫中有一個實體,它有一個null外鍵。Breeze在擴展時將外鍵值爲null的實體排除在外

當我通過JavaScript中的expand或EF中的Include時,具有該外鍵的行將丟失。

SQL:

CREATE TABLE Entity 
(
    Id BIGINT NOT NULL PRIMARY KEY 
); 

CREATE TABLE EntityType 
(
    Id BIGINT IDENTITY NOT NULL PRIMARY KEY, 
    EntityId BIGINT NULL REFERENCES Entity(Id) 
); 

INSERT INTO Entity(Id) VALUES (0); 
INSERT INTO Entity(Id) VALUES (1); 

INSERT INTO EntityType(EntityId) VALUES (0); 
INSERT INTO EntityType(EntityId) VALUES (1); 
INSERT INTO EntityType(EntityId) VALUES (NULL); 

C#:

public class Entity 
{ 
    public long Id { get; set; } 
} 

public class EntityType 
{ 
    public long Id { get; set; } 
    public long EntityId { get; set; } 
    public Entity Entity { get; set; } 
} 

public class EntityMap : EntityTypeConfiguration<Entity> 
{ 
    public EntityMap() 
    { 
     HasKey(t => t.Id); 
    } 
} 

public class EntityTypeMap : EntityTypeConfiguration<EntityType> 
{ 
    public EntityTypeMap() 
    { 
     HasKey(t => t.Id); 

     HasRequired(t => t.Entity) 
      .WithMany() 
      .HasForeignKey(t => t.EntityId); 
    } 
} 

[BreezeController] 
public class EntityController : ApiController 
{ 
    private readonly EFContextProvider<EntityContext> _contextProvider = 
     new EFContextProvider<EntityContext>(); 

    [HttpGet] 
    public IQueryable<Entity> Entities() 
    { 
     return _contextProvider.Context.Entities; 
    } 

    [HttpGet] 
    public IQueryable<EntityType> EntityType() 
    { 
     return _contextProvider.Context.EntityTypes; 
    } 
} 

JS:

angular.module('App').factory('EntityTypeService', function(serviceBase) { 
    function getAll { 
     return serviceBase.manager.executeQuery(
      serviceBase.query. 
       from('EntityTypes'). 
       expand('Entity') 
     ).to$q(); 
    } 

    return { 
     getAll: getAll 
    }; 
}); 

angular.module('App').controller('HomeCtrl', function($scope, EntityTypeService) { 
    EntityTypeService.getAll().then(function(data) { 
     $scope.entityTypes = data.results; 
    }); 
}); 

當我審視$scope.entityTypes有與EntityId不是null只有行。

回答

0

原來是EF的複製粘貼問題。

映射應該是HasOptional而不是HasRequired

public class EntityTypeMap : EntityTypeConfiguration<EntityType> 
{ 
    public EntityTypeMap() 
    { 
     HasKey(t => t.Id); 

     HasOptional(t => t.Entity) 
      .WithMany() 
      .HasForeignKey(t => t.EntityId); 
    } 
} 

這將產生所有行EntityType