I have the following code :
public Exam CreateExam(string name, List<Question> questions, DateTime timeNow)
{
User user = GetUserByName(name);
Exam exam = new Exam()
{
Questions = questions,
StartDate = timeNow,
User = user
};
Context.Exams.Add(exam);
Context.SaveChanges();
return exam;
}
Exam :
public class Exam
{
public int Id { get; set; }
public DateTime StartDate { get; set; }
public User User { get; set; }
public virtual List<Question> Questions { get; set; }
}
And user has the basic user infos.
My problem is that when I create an exam for the user, the save change also add a new user to the database, with only the ID being different. How do I prevent that and make it understand that I want to link it to the existing user ?
Thank you !
Edit: GetUserByName() :
Context.Database.SqlQuery<User>("Select * from Users where name = #name", new SqlParameter("name", name)).FirstOrDefault();
When you use SqlQuery to fetch user, he will not be tracked by Entity Framework, because you can write arbitrary query and map result to User class. So EF consider, that he is new one, when you reference to him. To fix this problem, you should manually attach his to context:
User user = GetUserByName(name);
Context.Users.Attach(user);
Based Slava Utesinov answer Entity Framework's change tracker does not track entity changes when get from raw query such as:
Context.Database.SqlQuery<User>("Select * from Users where name = #name", new SqlParameter("name", name)).FirstOrDefault();
Therefore when you call SaveChanges() method, Entity Framework change tracker detect user entity state as Added (new entity)
1.you can use DbSet.SqlQuery instead of Database.SqlQuery because DbSet.SqlQuery will tracked by the context:
Context.Users.SqlQuery("Select * from Users where name = #name", new SqlParameter("name", name)).FirstOrDefault();
or
2.you can attach entity to current context dbset as unchanged state
Related
In my .NET Core application with EF Core I get the following error:
The property 'RoleId' on entity type 'UserRole' is part of a key and so cannot be modified or marked as modified. To change the principal of an existing entity with an identifying foreign key first delete the dependent and invoke 'SaveChanges' then associate the dependent with the new principal.'
public class UserRole
{
public Guid RoleId { get; set; }
public virtual Role Role { get; set; }
public Guid UserId { get; set; }
public virtual User User { get; set; }
}
Why does it suggest to delete the row first and then create a new one. It should only update the role of the object and save it with the new one.
I have already tried to set the navigation properties (Role and User) to null, so it needs only to update the RoleId field with the new existing Role.Id.
I have tried to update the Role navigation itself with the new one.
But it doesn't matter.
What should I do to solve this?
A table like UserRole is a Many to Many joining table. In EF6 declaring these was optional where as long as the table just contained the UserID and RoleID, your User entity could simply have a Roles collection and the Role could optionally have a Users collection. When set up this way IMO it was easier to understand the limitation in that you wouldn't just take an existing Role reference and try to change it's ID.
AFAIK with EF Core you still need to map the joining table so User will have a collection of UserRoles and you have to navigate through that collection to get to the Roles from the User. Still, the behaviour for many-to-many relationships is the same, you do not modify these references, you need to remove and recreate them.
For instance, given:
var user = context.Users.Include(x => x.UserRoles).ThenInclude(x => x.Roles).Single(x => x.UserId == userId);
var newRole = context.Roles.Single(x => x.RoleId == newRoleId);
var userRole = user.UserRoles.SingleOrDefault(x => x.RoleId == oldRoleId);
//(Incorrect)
if (userRole != null)
userRole.Role = newRole;
//(Correct)
if (userRole != null)
user.UserRoles.Remove(userRole);
user.UserRoles.Add(new UserRole { User = user, Role = newRole });
My current employer is developing a mobile app using Xamarin.Forms and Asp.net mvc on the backend. I suggested to use realm in the mobile app. My manager want to see a POC(Proof of concept) app using realm with backlink feature before allowing it to be used in the app. I am working on the POC on GitHub . The documentation is very limiting and the GitHub repo of realm-dotnet don’t have good sample.
I completed the project. But unable to implement backlink. The sample app I have developed allow user to create assignees(employees) in the first page. The user can delete or edit the employees using context menu. When the user clicks on the employee name the app navigates to the ToDoListPage of that particular employee. Here the user can create ToDoItems. On this ToDoList page I want to show the ToDoItems that where assigned to that employee only.
The models were as follows:
public class Assignee : RealmObject
{
public Assignee()
{
ToDoItems = Enumerable.Empty<ToDoItem>().AsQueryable();
}
[PrimaryKey]
public string Id { get; set; } = Guid.NewGuid().ToString();
public string Name { get; set; }
public string Role { get; set; }
[Backlink(nameof(ToDoItem.Employee))]
public IQueryable<ToDoItem> ToDoItems { get; }
}
public class ToDoItem : RealmObject
{
[PrimaryKey]
public string Id { get; set; } = Guid.NewGuid().ToString();
public string Name { get; set; }
public string Description { get; set; }
public bool Done { get; set; }
public Assignee Employee { get; set; }
}
I am adding employee to each ToDo Item:
Item.Employee = Employee;
_realm.Add(Item);
Now I want to access the ToDoItems for the Employee:
Items = _realm.All<Assignee>().Where(x => x.Id == EmployeeId).FirstOrDefault().ToDoItems;
But this does not work. I will be grateful if someone can help me out by preferably writing code in my sample app or write the correct code in the reply.
Thank you
Firstly, Realm .NET doesn't currently support traversing properties (x.Employee.Id). Due to this, when I start the app and try to go to the ToDoListPage, the app crashes with the exception:
The left-hand side of the Equal operator must be a direct access to a persisted property in Realm
Realm supports object comparison, so we can fix this like so:
var employee = _realm.Find<Assignee>(EmployeeId);
Items = _realm.All<ToDoItem>().Where(x => x.Employee == employee);
Secondly, everything seemed fine in your code, so I dug a bit deeper and saw why it isn't working. The issue is that when we try to get all items with the code above, the EmployeeId parameter is null. Since the EmployeeId is being populated after the load logic has been triggered, we don't need to load the data in the ctor. So you can remove this code.
Finally, since you won't be loading the data in the ctor, and instead in the SetValues method, the UI needs to know, when the data has been updated, what exactly to redraw. Thus, you need to mark the collection to be Reactive too:
[Reactive]
public IEnumerable<ToDoItem> Items { get; set; }
Then, you need to change the SetValues method to use object comparison, instead of traversing:
async Task SetValues()
{
Employee = _realm.Find<Assignee>(EmployeeId);
Title = Employee.Name;
Items = _realm.All<ToDoItem>().Where(x => x.Employee == Employee);
}
To sum up - you don't need to try and load the data in the ctor, since you don't know when the EmployeeId will be set. You are already tracking when the property will change and inside the SetValues command you simply need to change the expression predicate.
i have some question regarding to edit/delete operation via asp.net mvc or web applications in general.
Lets say i have the following url to delete or edit records : app/delete/5, app/edit/5 to edit or delete record with id 5.
When calling the link, a confirmation page is loaded via HTTP GET and the edit/delete operation itself is done via HTTP POST.
Once user knows the link, how can i prevent him from calling any other app/delete or app/edit for records he does not own or is not permitted to edit/delete? Example: app/delete/7312
What do i have to put in my controller action that the user can only fetch the confirmation page via GET for the records he is permitted to execute an edit/delete?
Best regards
marc
Okay at first I posted a simpler answer but I didn't understand the question. You are going to need two things. A way to know who created what in the system, and then some business logic in the delete action checking if the current user is equal to the user who created it. I would suggest this inheritable class that i use to track ownership of an object:
public class BaseEntity
{
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = false)]
[Display(Name = "Date Created")]
[DataType(DataType.Date)]
public DateTime? DateCreated { get; set; }
public string UserCreated { get; set; }
[Display(Name = "Date Modified")]
[DataType(DataType.Date)]
public DateTime? DateModified { get; set; }
public string UserModified { get; set; }
}
Then in your database context class, you can overwrite save changes to automatically track these things whenever a user in the system saves something t o populate those fields. This is handy because you don't have to go into Create, Edit, etc. and manually link this up.
public override int SaveChanges()
{
var entities = ChangeTracker.Entries().Where(x => x.Entity is BaseEntity && (x.State == EntityState.Added || x.State == EntityState.Modified));
var currentUsername = HttpContext.Current != null && HttpContext.Current.User != null
? Users.Find(HttpContext.Current.User.Identity.GetUserId()).Name
: "Anonymous";
foreach (var entity in entities)
{
if (entity.State == EntityState.Added)
{
((BaseEntity)entity.Entity).DateCreated = DateTime.Now;
((BaseEntity)entity.Entity).UserCreated = currentUsername;
}
((BaseEntity)entity.Entity).DateModified = DateTime.Now;
((BaseEntity)entity.Entity).UserModified = currentUsername;
}
return base.SaveChanges();
}
Then finally, to actually achieve your functionality, you can in your controller's delete action only let the delete go through if Users.Find(HttpContext.Current.User.Identity.GetUserID()).name is equal to the name of whoever created the model.
I know this is a lot, if you have questions please comment I'll check in.
I have a Shop model which contains several fields. One of which is a virtual User one. Whenever I try to edit one entry I get an error saying that User field is required.
public class Shop
{
//..
public virtual ApplicationUser User { get; set; }
//..
}
My workaround is this:
shop.User = shop.User; //re-set the value
shop.Active = true;
db.Entry(restaurant).State = EntityState.Modified;
db.SaveChanges();
And I have to do this for all the fields. Is this the standard approach for this or is there a better way?
Change your model to this:
public class Shop
{
//..
public int UserId {get; set; }
public virtual ApplicationUser User { get; set; }
//..
}
Entity Framework will automatically detect that UserId is the foreign key for object User. You had this problem because User is virtual (lazy loaded). When changing the model without accessing or setting this property EF thinks it's empty (I assume). The foreign key UserId is not virtual, and will be fetched together with the other properties of model Shop, so you don't have to re-set the value when saving the model.
To set a new user, you now have to do for example:
myShop.UserId = 1; // instead of setting myShop.User
For more information, see this article: http://msdn.microsoft.com/en-us/data/jj713564.aspx
I am new with EF Code First and have some troubles with it.
Here my Model
public class User
{
public string Id { get; set; }
public string Name { get; set; }
public virtual Address Address { get; set; }
}
public class Address
{
public string Id { get; set; }
public string Street { get; set; }
public string Nr { get; set; }
}
What I want is, if I write the following code:
user.Address = null;
the related Address (record in database) should be deleted, but it is not! It removes only the foreign key in Users table. Also when I assign a new Address:
user.Address = new Address() { ... };
it is created a second record in database, why?
I want:
if assign null to user.Address the database record should be deleted
if assign a new Address object to user.Address it should replace the existing records data with the new one
How can I solve this?
If you need to delete an entity you need to mark it as deleted. Setting a navigation property to null will not delete the related entity. Note that there may be many navigation properties (different entities) pointing to the related entity and they all would be affected in the scenario you are describing.
Because you create a new Address a new entity is created. Then you set your navigation property to a newly created property this breaks the old relationship and creates a new one. Since the entity you created is not in the database it will be added. You also did not delete the old entity so it was not deleted from the database. If you just want to change property values of an entity just set properties to new values and invoke SaveChanges. This should update data in the database.