Entity Framework Core Can't Add Entity but can Select it - entity-framework

My problem is:
I can select a entity normally, but when a try to add it, i'm receiving the exception:
ORA-06550: linha 3, coluna 22:
PL/SQL: ORA-00942: table or view does not exist
ORA-06550: linha 3, coluna 1:
PL/SQL: SQL Statement ignored
Context below:
My database: Oracle
Owner (schema that have the data): XXX
User on connect (user that have permissions to select, insert, etc): YYY.
I'm ensure the grants its ok. I can insert mannualy the data.
My Entity on my API it's declared like:
[Table("TABLE_NAME", Schema = "XXX")]
public class AnalyzeFeedback
Select ok
IQueryable<AnalyzeFeedback> analyzeFeedbacks = dbContext.AnalyzeFeedbacks;
var query = (from u in analyzeFeedbacks
select u);
var sql = query.ToSql();
var result = query.FirstOrDefault();
This select returns the first record of my table. Perfectly.
When I try to add a new record:
Insert problem:
Exception on SaveChanges
dbContext.AnalyzeFeedbacks.Add(feedback);
dbContext.SaveChanges();
On "SaveChanges" it's when i'm getting the error.
Sorry if i'm not clear enough on my explanation.

Also does AnalyzeFeedback have any reference properties/fields
This is exactly my problem man, thanks.
My entity have a property that not correctly tagged:
[ForeignKey("AnalyzeId")]
public Analyze Analyze { get; set; }
[NotMapped] <<< this!
public List<AnalyzeFeedbackBasement> Basements { get; set; }
When a tagged like "NotMapped", the insert occoured like expected.
Thanks for your reply Gullard!!

Related

EF Core - Change column type from varchar to uuid in PostgreSQL 13: column cannot be cast automatically to type uuid

Before:
public class MyEntity
{
public string Id { get; set; }
//...
}
Config:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
//...
modelBuilder.Entity<MyEntity>()
.Property(e => e.Id)
.ValueGeneratedOnAdd();
}
This was the previous developer's code which resulted in GUID values for the column. But in C# I had to deal with strings, so I decided to change the model.
After:
public class MyEntity
{
public Guid Id { get; set; }
//...
}
And I removed the ValueGeneratedOnAdd() code from Fluent API config.
I get the column "Id" cannot be cast automatically to type uuid error.
I think the key in this message is the automatically word.
Now my question is that since the values on that column are already GUID/UUID, is there any way to tell Postgres to change the varchar type to uuid and cast the current string value to UUID and put it in the column? I'm guessing there should be a SQL script that can do this without any data loss.
Use USING _columnname::uuid. Here is an illustration.
-- Prepare a test case:
create table delme (x varchar);
insert into delme (x) values
('b575ec3a-2776-11eb-adc1-0242ac120002'),
('4d5c5440-2776-11eb-adc1-0242ac120002'),
('b575f25c-2776-11eb-adc1-0242ac120002');
-- Here is the conversion that you need:
ALTER TABLE delme ALTER COLUMN x TYPE uuid USING x::uuid;
In your particular case:
ALTER TABLE "MyEntity" ALTER COLUMN "Id" TYPE uuid USING "Id"::uuid;
Btw, is your application the sole owner of the database model? If not then changing an existing table is a bad idea.

Fetching id field of an entity in the SQL Transaction

I have the following schema.
Person(pid, pname)
Beer(bid, bname)
Likes(pid,bid)
I would like to insert a likes item. However, I am accepting the following format for the new users : (Pid, pname, bid, bname).
I would like to create a transaction for that to avoid conflict ( This is a highly simplified version of my real problem but the issue is the same). In my Person table, I set pid Auto-Increment(or Serial in Postgresql). Also the same goes for bid.
I have stuck in a point where I know the Person does not exist but the beer exists. So, I have to create a Person, then add an entity to Likes relation.
As far as I know, when I use the Autocommit(false) in dB, the transaction won't save until the commit. So, should I change the db design:
Change the auto-increment field to a normal integer, not null field.
In the transaction, after the autoCommit(false) has begun, read the last entry of the person
Increment it by one while creating the new person
Then create likes relation
Or, is there any other way around or do I miss something about transactions?
Here is what I have done so far:
try {
String add_person_sql = "INSERT INTO Person (name) VALUES(?)";
PreparedStatement add_person_statement = mydb.prepareStatement(add_person_sql);
String add_likes_sql = "INSERT INTO Likes (pid, bid) VALUES(?, ?)";
PreparedStatement add_likes_statement = mydb.prepareStatement(add_likes_sql);
mydb.setAutoCommit(false);
add_person_statement.setString(1, pname);
// The problem is, without saving the person I cannot know the id of the person
// AFAIK, this execution is not finished until commit occurs
add_person_statement.executeQuery();
// How can I fetch person's id
add_likes_statement.setString(1, pid);
add_likes_statement.setString(2, bid);
add_likes_statement.executeQuery();
mydb.commit();
}
catch(Exception e){
System.out.println(e);
mydb.rollback();
}
You can tell JDBC to return the generated ID from the insert statement, then you can use that ID to insert into the likes table:
mydb.prepareStatement(add_person_sql, new String[]{"pid"});
The second parameter tells the driver to return the generated value for the pid column.
Alternatively you can use
mydb.prepareStatement(add_person_sql, Statement.RETURN_GENERATED_KEYS);
that tells the driver to detect the auto increment columns.
Then run the insert using executeUpdate()
add_person_statement.setString(1, pname);
add_person_statement.executeUpdate();
int newPid = -1;
ResultSet idResult = add_person.getGeneratedKeys();
if (idResult.next()) {
newPid = idResult.getInt(1);
}
add_likes_statement.setString(1, newPid);
add_likes_statement.setString(2, bid);
add_likes_statement.executeUpdate();
mydb.commit();

Get Record ID in Entity Framework 5 after insert

I realize this must be a relatively simple thing to do, but I'm not getting what I'm looking for with Google.
I need to get the record ID of the record I just saved using the Entity Framework. With SQL queries we used "Select ##IDENTITY as 'Identity';"
If anyone can help it would be greatly appreciated.
The default behavior of Entity Framework is it sets identity fields on entities from the database right after SaveChanges is called.
In the following sample code, before SaveChanges is called, my employee has a default ID of 0. After SaveChanges my employee has a generated ID of 1.
using (TestDbEntities context = new TestDbEntities())
{
Employee e = new Employee ();
e.FirstName = "John";
e.LastName = "Doe";
context.Employee.Add(e);
context.SaveChanges();
Console.WriteLine("Generated ID: {0}", e.ID);
Console.ReadKey();
}

Many-to-Many insert failing - Entity Framework 4.1 DbContext

I am using DB first method, EF 4.1 with DbContext POCO code gen.
My database has a many-to-many relationship as shown below:
Employee
EmployeeId
EmployeeName
Account
AccountId
AccountName
EmployeeAccount
EmployeeId
AccountId
The problem occurs when I am trying to insert a new Employee, and assign them a pre existing account, so I am basically doing this as below:
Employee emp = new Employee();
emp.EmployeeName = "Test";
emp.Accounts.Add(MethodThatLooksUpAccountByName("SomeAccountName"));
context.Employees.Add(emp);
context.SaveChanges();
The SQL this is executing (incorrectly), is attempting to INSERT a new [Account] record, and this is failing on a constraint violation. Of course, it should not INSERT a new [Account] record, it should only insert a new [EmployeeAccount] record, after inserting the [Employee].
Any advice? Thanks.
MethodThatLooksUpAccountByName does this method return an attached or detached object? In any case, you may try to attach the object it returns to the context.
Employee emp = new Employee();
emp.EmployeeName = "Test";
var acc = MethodThatLooksUpAccountByName("SomeAccountName");
context.Attach(acc); //I don't remember if it's attach or attachobject, but intellisense should help you there.
emp.Accounts.Add(acc);
context.Employees.Add(emp);
context.SaveChanges();

can't delete object that has a many-to-many relationship

these are my simplified entities:
public class User : Entity
{
public virtual ICollection<Role> Roles { get; set; }
}
public class Role : Entity
{
public virtual ICollection<User> Users { get; set; }
}
var user = dbContext.Set<User>().Find(id);
dbContext.Set<User>().Remove(user);
dbContext.SaveChanges(); // here i get error (can't delete because it's the
//referenced by join table roleUsers
the problems is that the join table references the user table and ef doesn't remove the records from the join table before deleting the user
I tried writing test cases and I noticed that:
if use the same context to add user with roles, save changes, remove and again save changes it works
but if I use 2 different contexts one for insert and another one for delete I get this error
You must first clear Roles collection (user's roles must be loaded) before you will be able to remove user.
If you want to just get this deleting just do what the error is saying.
as a part of your DELETE method, you should do this, in order.
1) Get User including its related roles you can user User.Include(r=>r.roles)
2) iterate through and delete the roles for the given user (make sure you use a toList() when you do this loop )
3) Delete the user
4) savechanges
user.Roles
.ToList()
.ForEach(role => user.Roles.remove(role));
context.Users.remove(user);
context.SaveChanges();