Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
553 views
in Technique[技术] by (71.8m points)

c# - Oracle ODP.Net and EF CodeFirst - SaveChanges Error

Could someone help me with this:

The code:

Role r = new Role { ID = 1, Name = "Members" };
ctx.Roles.Attach(r);

//Saving User
User u = new User {
    Login = login,
    Password = password,
    Status = 1
};
u.Roles.Add(r);

ctx.Users.Add(u);
ctx.SaveChanges();

What I'm trying to do is to save a new user with an existing role. User and Role classes have a many-to-many relationship mapped by fluent-api as follows:

modelBuilder.Entity<User>()
.HasMany(u => u.Roles)
.WithMany(r => r.Users)
.Map(x => {
    x.ToTable("USER_ROLE_XREF", dbsch);
    x.MapLeftKey("ID_USER");
    x.MapRightKey("ID_ROLE");
});

But when the SaveChanges is called I get this error: {"The specified value is not an instance of type 'Edm.Decimal' Parameter name: value"}

Actually, always I try to save related entities with a single SaveChanges() call I get the same error. so, what I had to do to figure this was to make multiple calls and so works well:

Role r = new Role { ID = 1, Name = "Members" };
ctx.Roles.Attach(r);

//Saving User
User u = new User {
    Login = login,
    Password = password,
    Status = 1
};

ctx.Users.Add(u);
ctx.SaveChanges();

//Assigning Member Role
u.Roles.Add(r);
ctx.SaveChanges();

It is my understanding that EF support to save multiple changes with a single SaveChanges call, so I'm wondering what's wrong here.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The idea with the Attach() method is that you have an entity that is known to be in the DB but not being tracked by this context, right? My question to you is do you know for sure that this Role here:

Role r = new Role { ID = 1, Name = "Members" };

is something that exists already? If it doesn't, I don't think what you want to do is use

ctx.Roles.Attach(r);

rather it is that you'd write:

ctx.Roles.Add(r);

and then you could turn around and write

User u = new User {
    Login = login,
    Password = password,
    Status = 1,
};

ctx.Users.Add(u);
u.Roles.Add(r);
ctx.SaveChanges();

The issue your first example has is that this new Role is really new to the DB so attaching it isn't what you'd want to do, rather you'd want to Add it.

And the single call to ctx.SaveChanges() should work just fine here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...