如何在不保存相关实体的新版本的情况下将实体与实体相关联

时间:2015-03-18 01:15:23

标签: c# entity-framework

我有两个实体:

public class FileUploadType
{
    [Key]
    public int FileUploadTypeID { get; set; }

    public string Key { get; set; }
}

public class File
{
    [Key]
    public int FileID { get; set; }        

    public FileUploadType FileUploadType { get; set; }
    ...
}

当我尝试将FileUploadType附加到我的控制器中的文件然后运行我的存储库Insert方法时,它会创建一个全新的FileUploadType:

File file = new File();

file.ItemID = Convert.ToInt32( itemID );
file.FileUploadType = this.fileUploadTypeRepository.GetByKey( uploadType );
this.fileRepository.Insert( file );

我的存储库看起来像这样:

public class EFFileRepository : EFGenericRepository<File>, IFileRepository
{
    ...

我的Generic是这样的:

public class EFGenericRepository<T> where T : class
{
    internal protected EFDbContext context = new EFDbContext();
    internal protected DbSet<T> dbSet;
    ...

    public virtual T Insert( T entityToInsert )
    {
        ...

        dbSet.Add( entityToInsert );
        context.SaveChanges();

        return entityToInsert;
    }

我的Db上下文如下所示:

public class EFDbContext : IdentityDbContext<ApplicationUser>
{
    public DbSet<File> Files { get; set; }
    public DbSet<FileUploadType> FileUploadTypes { get; set; }

    protected override void OnModelCreating( DbModelBuilder modelBuilder )
    {
        // base.OnModelCreating( modelBuilder );
        Precision.ConfigureModelBuilder(modelBuilder);

        modelBuilder.Entity<IdentityUserLogin>().HasKey<string>( l => l.UserId );
        modelBuilder.Entity<IdentityRole>().HasKey<string>( r => r.Id );
        modelBuilder.Entity<IdentityUserRole>().HasKey( r => new { r.RoleId, r.UserId } );
    }

    public static EFDbContext Create()
    {
        return new EFDbContext();
    }
}

0 个答案:

没有答案