实体框架一对一关系,断开连接的实体

时间:2015-08-18 15:55:13

标签: entity-framework ef-code-first

我想使用断开连接的对象。在我的模型中,用户可以拥有或不拥有地址。

首先是我的模特:

public class ApplicationUser : IdentityUser, IUser
{
    public ApplicationUser() : base()
    {
    }

    public virtual string FirstName { get; set; }
    public virtual string LastName { get; set; }
    public virtual DateTime BornDate { get; set; }
    public virtual SubscriptionSetting SubscriptionSetting { get; set; }

    public virtual Address Address { get; private set; }

    public void AddAddress(Address address)
    {
        this.Address = address;
    }
}

public class Address
{
    public Address(string id, string number, string type, string nom, string postalCode, string city, GPSCoordinates gps)
    {
        this.Id = id;
        this.Number = number;
        this.Type = type;
        this.Nom = nom;
        this.PostalCode = postalCode;
        this.City = city;
        this.GPSCoordinates = gps;
    }

    public virtual string Id { get; set; }
    public virtual string Number { get; set; }
    public virtual string Type { get; set; }
    public virtual string Nom { get; set; }
    public virtual string PostalCode { get; set; }
    public virtual string City { get; set; }
    public virtual GPSCoordinates GPSCoordinates { get; set; }
}

我的背景:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext() : base("DefaultConnection")
    {
        this.Database.Log = Console.Write;
    }

    public DbSet<Address> Addresses { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        modelBuilder.Configurations.Add(new SubscriptionSettingConfiguration());
        modelBuilder.Configurations.Add(new ApplicationUserConfiguration());
        modelBuilder.Configurations.Add(new AddressConfiguration());

        base.OnModelCreating(modelBuilder);
    }
}

我的配置:

public class ApplicationUserConfiguration : EntityTypeConfiguration<ApplicationUser>
{
    public ApplicationUserConfiguration() : base()
    {
        HasRequired(u => u.Address).WithRequiredPrincipal();
        Property(u => u.BornDate).HasColumnType("datetime2");
    }
}

public class AddressConfiguration : EntityTypeConfiguration<Address>
{
    public AddressConfiguration()
    {
        Property(m => m.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
        HasKey(m => m.Id);
    }
}

我的回购:

public virtual async Task<TEntity> InsertAsync(TEntity entity)
{
        DbSet.Add(entity);

        try
        {
            await _dbContext.SaveChangesAsync();
        }
        catch (DbEntityValidationException ex)
        {
            var sb = new StringBuilder();

            foreach (var failure in ex.EntityValidationErrors)
            {
                sb.AppendFormat("{0} failed validation\n", failure.Entry.Entity.GetType());

                foreach (var error in failure.ValidationErrors)
                {
                    sb.AppendFormat("- {0} : {1}", error.PropertyName, error.ErrorMessage);
                    sb.AppendLine();
                }
            }

            throw new DbEntityValidationException(
                "Entity Validation Failed - errors follow:\n" +
                sb.ToString(), ex
            );
        }

        return entity;
}

最后我的单元测试:

public class adress_repository_test
{
    IRepository<Address> _addressRepository;
    DbContext _context;

    public adress_repository_test()
    {
        _context = new ApplicationDbContext();
        _addressRepository = new Repository<Address>(_context);
    }

    [Fact]
    public async Task insert_new_address_success()
    {
        GPSCoordinates gps = new GPSCoordinates(44.5, 41.2);
        Address address = new Address("d0ead995-ca31-4950-bfd3-93e0ca82e37e", "BATC", "Allée", "beethoven", "60100", "creil", gps);
        var result = await _addressRepository.InsertAsync(address);
        Assert.NotEmpty(address.Id);
    }

测试运行时抛出异常:

  

违反PRIMARY KEY约束&#39; PK_dbo.Address&#39;。无法插入   对象&#39; dbo.Address&#39;中的重复键。重复的键值是   (d0ead995-ca31-4950-bfd3-93e0ca82e37e)

1 个答案:

答案 0 :(得分:0)

很抱歉这个问题,但我没有考虑我的测试配置,连接字符串不存在,它创建了一个新的数据库。 史蒂夫是对的,BDD中存在行