【问题标题】:Breeze is excluding entities with foreign key of null when they are expandedBreeze 在扩展时排除外键为 null 的实体
【发布时间】:2014-02-07 17:30:33
【问题描述】:

我的数据库中有一个具有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 的行。

【问题讨论】:

    标签: c# javascript entity-framework angularjs breeze


    【解决方案1】:

    原来是 EF 的复制粘贴问题。

    映射应该是HasOptional 而不是HasRequired

    public class EntityTypeMap : EntityTypeConfiguration<EntityType>
    {
        public EntityTypeMap()
        {
            HasKey(t => t.Id);
    
            HasOptional(t => t.Entity)
               .WithMany()
               .HasForeignKey(t => t.EntityId);
        }
    }
    

    这将产生EntityType的所有行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-24
      • 2021-09-03
      • 2013-04-18
      • 2013-06-18
      • 2013-08-10
      • 2018-11-18
      相关资源
      最近更新 更多