简体   繁体   中英

entity framework 6.1 - assign a forigen key cause to an insertion of new record

I seen similar posts but didn't find an answer. I have WPF 4.5 application with EF 6.1.

Here is my part of my data model:

[Key]
[Required]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int Id { get; set; }

[Required]
[StringLength(32)]
public string FileDisplayName { get; set; }

[Required]
[StringLength(32)]
public string FileName { get; set; }

[Required]
[StringLength(8)]
public string FileExtention { get; set; }

[StringLength(1024)]
public string Description { get; set; }

[Required]
[StringLength(1024)]
public string FilePath { get; set; }

[Required]
public DateTime UploadDate { get; set; }

[Required]
public virtual FilesTypeLookup FileType { get; set; }

[Required]
[DefaultValue(0)]
public double Amount { get; set; }

[Required]
public virtual Expenses ExpenseId { get; set; }

public virtual ExpensesCategories Category { get; set; }

public virtual ExpensesPayees Payee { get; set; }



public class ExpensesCategories
{
    [Key]
    [Required]
    public int Id { get; set; }

    [Required]
    [StringLength(64)]
    [Index(IsUnique = true)]
    public string Name { get; set; }

    [StringLength(256)]
    public string Description { get; set; }
}

As you can see, File entity has ExpensesCategory navigation property. The problem happens when I'm assigning new value for this property. I'm using the next code to editing existing File record:

   var fileEntity = entityToEdit.Files.Single(p => p.Id == file.Id);
                                fileEntity.Amount = file.Amount;
                                fileEntity.Category = DB.ExpensesCategories.Single(p => p.Id == file.Category.Id);
//more work here
context.SaveChanges();

The SaveChanges() method is firing an exception:

System.Data.Entity.Infrastructure.DbUpdateException An error occurred while updating the entries. See the inner exception for details. Int32 SaveChanges()
UpdateException An error occurred while updating the entries. See the inner exception for details. Int32 Update()
SqlException Cannot insert duplicate key row in object 'dbo.ExpensesCategories' with unique index 'IX_Name'. The duplicate key value is (חומרי יצירה).
The statement has been terminated. Void OnError(System.Data.SqlClient.SqlException, Boolean, System.Action`1[System.Action])

It seems that instead of create a relationship between existing File record to existing ExpenseCategory , EF is trying to create a new ExpenseCategory record and link it with my existing File record. The unique constraint does not allows it and fires the exception.

I don't want that EF will create new ExpenseCategory records, just want to set relationships with existing records ( ExpenseCategory is look-up table). How can I do this?

Thanks Ofir

Can you try this, add this to the ExpensesCategories class:

public virtual ICollection<Files> Files { get; set; }

Not sure if that will fix it but it's something that's missing anyway.

If there is one to one relationship between two objects you should add the following properties to the ExpensesCategories

[Key, ForeignKey("File")]    
public int FileId {get;set;}

public virtual File File{ get; set;}

In my opinion the relation ship between ExpensesCatrgories and Files is one to many (one category has may files but each file belongs to a specific category). In this case please add

public virtual ICollection<File> Files { get; set; } 

to the ExpensesCategories

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM