Cannot add an entity with a key that is already in use. How to solvethis?

S

shapper

Hello,

I am creating two Assets using LinqToSQL as follows:

ISession session = new Context();
AssetRepository assetRepository = new AssetRepository(session);
assetRepository.Create(new Asset { Id = 1, Mime = new Mime { Id
= 9 }});
assetRepository.Create(new Asset { Id = 2, Mime = new Mime { Id
= 9 }});
session.Commit();

Session implements Unit of Work pattern:

public interface ISession {
void Commit();
void Rollback();
} // ISession

public partial class Context : DataContext, ISession {
public void Commit() {
SubmitChanges();
} // Commit
public void Rollback() {
Dispose();
} // Rollback
} // Context

What ever I do I always get the following error:
"Cannot add an entity with a key that is already in use."

On code line:
_context.Mimes.Attach(mime);

On my repository create asset code:
public void Create(AssetModel asset) {

// Define entity
Asset _asset = new Asset { Id = asset.Id};
_context.Assets.InsertOnSubmit(_asset);

if (asset.Mime != null) {
Mime mime = new Mime { Id = asset.Mime.Id };
_context.Mimes.Attach(mime);
_asset.Mime = mime;
}

} // Create

Basically, in each Asset there is a MimeId.

Anyway, is there a way to overcome this?
I am really not sure what am I doing wrong.

Here is the SQL code for Assets and Mimes:

create table dbo.Assets
(
Id int not null,
MimeId int not null,
constraint PK_Assets primary key clustered(Id)
) -- Assets

create table dbo.Mimes
(
Id int not null,
Type nvarchar(80) not null,
constraint PK_Mimes primary key clustered(Id)
) -- Mimes

alter table dbo.Assets
add constraint FK_Assets_Mimes foreign key(MimeId) references dbo.Mimes
(Id) on delete no action on update cascade;

Note: Assets table has more columns, like Content, etc ...
But for sake of simplicity I am not including this on my
code as I am just testing the relations.

Could someone tell me how should I solve this?

Thanks,
Miguel
 
K

Kosmo

      assetRepository.Create(new Asset { Id = 1, Mime = new Mime { Id
= 9 }});
      assetRepository.Create(new Asset { Id = 2, Mime = new Mime { Id
= 9 }});

Here you are trying to insert two records with same primary key value
9 into table. That's the problem.
        _context.Mimes.Attach(mime);

Would be nice to have the code of this method attached.
I think, inside should be check if there is already entry in table
with same id.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top