One-to-one property in EF 6 does not update. - ef-code-first

I am using Entity Framework 6 with Code First.
Model:
public class UserProfile
{
[Key]
public Guid UserID { get; set; }
public Language PreferredLang { get; set; }
//more properties
}
UserProfile table is generated with PreferredLang_LanguageID column. I wrote following method to save user profile. If this UserID is found in DB, I update, otherwise I add row.
public static void UpdateProfile(UserProfile userProfile)
{
using (var db = new Context())
{
if (db.UserProfiles.Any(p => p.UserID == userProfile.UserID))
{
//does not save language properly
db.UserProfiles.Attach(userProfile);
db.Entry(userProfile).State = System.Data.Entity.EntityState.Modified;
db.Entry(userProfile.PreferredLang).State = System.Data.Entity.EntityState.Modified;
}
else
{
//duplicates language
db.UserProfiles.Add(userProfile);
}
db.SaveChanges();
}
}
There are two problems.
When I create new UserProfile (db.UserProfiles.Add), new entry for Language is created, even though Language already existed. PreferredLanguage had ID = 2, and after db.SaveChanges, it created new Language with ID = 5 (smallest available) and set PreferredLang_LanguageID = 5. How can I use existing Language?
When I update existing UserProfile, then all properties (columns) are updated in DB, except for `PreferredLang_LanguageID. This one stays the same. How could Language be updated?

To answer first part of question - saving without creating new entry for Language. I attached PreferredLang:
{
db.UserProfiles.Add(userProfile);
db.Languages.Attach(userProfile.PreferredLang);
}
db.SaveChanges();

I know that this is not the most elegant solution, but it's the only one that worked for me. If existing entry is found, then it is removed and new instance is attached to context:
if (db.UserProfiles.Any(p => p.UserID == userProfile.UserID))
{
//not elegant, but only solution that works
db.UserProfiles.Remove(db.UserProfiles.Find(userProfile.UserID));
}
db.UserProfiles.Add(userProfile);
db.Languages.Attach(userProfile.PreferredLang);
db.SaveChanges();

Related

Unwanted unique constraint in many to many relationship

I'm trying to set up a Tagging tool for images. Basically I have two tables, one for pictures, and one for tags. Both are connected with a many to many setup. I can already add a single tag to a picture, and the same tag to different pictures. However, when I try to add a second tag to an image I get an exception complaining about a unique constraint that I simply don't see.
public class MediaEntity
{
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<TagEntity> Tags { get; set; }
}
public class TagEntity
{
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<MediaEntity> MediaEntities { get; set; }
}
public void updateMedia(MediaEntity model)
{
using (var db = new MediaContext(_dbLocation))
{
db.Update(model);
db.SaveChanges();
}
}
public class MediaContext : DbContext
{
private const string DB_NAME = "PT.db";
private string _path;
public DbSet<MediaEntity> MediaTable { get; set; }
public DbSet<TagEntity> TagTable { get; set; }
public MediaContext(string path)
{
_path = path;
ChangeTracker.AutoDetectChangesEnabled = false;
}
protected override void OnConfiguring(DbContextOptionsBuilder options)
=> options.UseSqlite($"Data Source={Path.Combine(_path, DB_NAME )}");
}
As far as I can tell my setup should create a normal many-to-many relationship, and it the database I also see pretty much this. EF automatically creates a TagTable, MediaTable, and MediaEntityTagEntityTable. But when I try to add a second tag I get this:
SqliteException: SQLite Error 19: 'UNIQUE constraint failed:
MediaEntityTagEntity.MediaEntitiesId, MediaEntityTagEntity.TagsId'.
Data from the table showing I can have the same tag on different pictures:
MediaEntitiesId
TagEntitiesId
1B48E85B-F097-4216-9B7A-0BA34E69CBFF
CF581257-F176-4CDF-BF34-09013DCEAA27
CE33F03F-5C80-492B-88C6-3C40B9BADC6C
CF581257-F176-4CDF-BF34-09013DCEAA27
523178A1-C7F8-4A69-9578-6A599C1BEBD5
0C45C9D1-7576-4C62-A495-F5EF268E9DF8
I don't see where this unique constaint comes in. How can I set up a proper many-to-many relationship?
I suspect the issue you may be running into is with the detached Media and associated Tags you are sending in. You are telling EF to apply an 'Update' to the media, but the DbContext will have no idea about the state of the Tags attached. Assuming some tags may have been newly attached, others are existing relationships. If the Context isn't tracking any of these Tags, it would treat them all as inserts, resulting in index violations (many to many) or duplicate data (many to one / one to many)
When dealing with associations like this, it is generally simpler to define more atomic actions like: AddTag(mediaId, tagId) and RemoveTag(mediaId, tagId)
If you are applying tag changes along with potential media field updates in a single operation I would recommend rather than passing entire entity graphs back and forth, to use a viewModel/DTO for the tag containing a collection of TagIds, from that apply your tag changes against the media server side after determining which tags have been added and removed.
I.e.:
public void updateMedia(MediaViewModel model)
{
using (var db = new MediaContext(_dbLocation))
{
var media = db.Medias.Include(x => x.Tags).Single(x => x.MediaId = model.MedialId);
// Ideally have a Timestamp/row version number to check...
if (media.RowVersion != model.RowVersion)
throw new StaleDataException("The media has been modified since the data was retrieved.");
// copy media fields across...
media.Name = model.Name;
// ... etc.
var existingTagIds = media.Tags
.Select(x => x.TagId)
.ToList();
var tagIdsToRemove = existingTagIds
.Except(model.TagIds)
.ToList();
var tagIdsToAdd = model.TagIds
.Except(existingTagIds)
.ToList();
if(tagIdsToRemove.Any())
media.Tags.RemoveRange(media.Tags.Where(x => tagIdsToRemove.Contains(x.TagId));
if(tagIdsToAdd.Any())
{
var tagsToAdd = db.Tags.Where(x => tagIdsToAdd.Contains(x.TagId)).ToList();
media.Tags.AddRange(tagsToAdd);
}
db.SaveChanges();
}
}
Using this approach the DbContext is never left guessing about the state of the media and associated tags. It helps guard against stale data overwrites and unintentional data tampering (if receiving data from web browsers or other unverifiable sources), and by using view models with the minimum required data, you improve performance by minimzing the amount of data sent over the wire and traps like lazy load hits by serializers.
I always explicitly create the join table. The Primary Key is the combination of the two 1:M FK attributes. I know EF is supposed to map automatically, but since it isn't, you can specify the structure you know you need.

Data always filled by null in dbcontext in .net core 3.1 api

Dears, I am using a dbfirst API . net core 3.1.
I created a migration file to apply stored procedure, and it is successfully created.
protected override void Up(MigrationBuilder migrationBuilder)
{
string procedure1 = #"CREATE PROCEDURE [dbo].[Spz_order] #client varchar(10) as
SELECT .....
having ... =#client";
migrationBuilder.Sql(procedure1);
}
Then I created a model or class to receive the data in it
[NotMapped]
public partial class categoryStock
{
public string model { get; }
public int quantity { get; }
}
Then a dbset
public virtual DbSet<categoryStock> Categories { get;}
Then in controller
[HttpGet("getCategoryStock")]
public async Task<List<categoryStock>> getCategoryStock(string cat)
{
using (_context)
{
if (_context.Categories != null)
{
var category =await _context.Categories
.FromSqlRaw("EXECUTE Spz_order {0}", cat)
.ToListAsync();
return category.ToList();
}
return new List<categoryStock>();
}
}
BUT i always get data by null, can any one help me to solve this issue
Thanks in advance
First, please check your database, make sure the data table contains records.
Second, please check your query statement in the stored procedure, make sure the query result is not null.
Third, please check the parameter value, make sure it is correct and you can find records according to the value.
Edit:
Perhaps the issue is related to the [NotMapped] attribute. The NotMapped attribute is used to specify that an entity or property is not to be mapped to a table or column in the database.
According to your code, I have created a model without using the NotMapped attribute, then, I can call the stored procedure and get the data.
Code as below:
public IActionResult Index()
{
var title = "G";
var param = new SqlParameter("#Title", "Rio");
//var movies = context.Movie
// .FromSqlRaw("GetMovies #Title", param)
// .ToList();
var movies = context.Movie
.FromSqlRaw("EXECUTE GetMovies {0}", title)
.ToList();
return View();
}
The screenshot:
So, try to remove the [NotMapped] attribute.

Update database items from the website

My current problem is (probably) not necessarily directly related to MVC 6, but how working with database actually works, and therefore any help/suggestions in this matter would be more than appreciated.
For the sake of this question, let's say that we have a very simple database with the following tables (C# classes) [we are using Entity Framework to work with the database]:
public class ShoppingUser
{
public int Id { get; set; }
public string UserName { get; set; }
public ICollection<ShoppingItem> Items { get; set; }
}
public class ShoppingItem
{
public int Id { get; set; }
public string Quantity { get; set; }
public string Text { get; set; }
public bool ToRemove { get; set; }//if item has been bought, it can be removed from the shopping list
}
This demo will be for a super duper simple shopping list app, where user (ShoppingUser who is registered in the system can have a List of ShoppingItem where user can decide on what is the text of the item (e.g. Bread, Butter, Tomatoes, ...) and also a quantity (3 pieces, 5kg, ... simple string)
Afterwards in my ASP.NET Core app, I have defined a repository which is communicating with the database and has access to the ShoppingItem class (as we are only interested in shopping items of currently logged in user).
Example of some method we could use here:
public IEnumerable<ShoppingItem> ReturnUserItems(string sUsername)
{
if (string.IsNullOrWhiteSpace(sUsername))
return null;
var result = _context.ShoppingUsers.Include(n => n.Items).Where(n => n.UserName == sUsername).FirstOrDefault();
if (result != null)
return result.Items;
else
return null;
}
Finally we have an API controller with JsonResult for either GET, POST, DELETE, ..., which is used for communication between client side AngularJs App and our server side logic.
Example of GET Method:
// GET: /<controller>/
[HttpGet("")]
public JsonResult Get(string sUserName)
{
try
{
var results = _repository.ReturnUserItems(User.Identity.Name);
if (results != null)
{
var result = Mapper.Map<IEnumerable<ShoppingItemViewModel>>(results);
return Json(result);
}
Response.StatusCode = (int)HttpStatusCode.OK;
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(new { Message = ex.Message });
}
return null;
}
Here comes the tricky part (at least for me). From video tutorials I have learned, that I should never (or almost never) expose my real database model to the website (I guess it's for security reasons). Due to that (as visible from my GET method above) I have declared my ShoppingItemViewModel which contains only properties I want to expose to the user (e.g. meaning that Id of my item is not visible).
This is how it looks like:
public class ShoppingItemViewModel
{
public string Quantity { get; set; }
[Required]
public string Text { get; set; }
[Required]
public bool ToRemove { get; set; }//if item has been bought, it can be removed from the shopping list
}
And for the communication from my AngularJS App I am using simple $http.get and $http.post calls for retrieving / posting updated data.
Finally the question:
My problem is, that if a user decides to either delete an item from his shopping list, or decides to change the content of either text / quantity (meaning that originally in the database it was tomatoes - 5 kg but he manages to buy only 2 kg and therefore changes the quantity to tomatoes - 3kg), how can the app understand which elements have actually been changed and how? The problem I have in this case is, that we are no longer exposing the database Id of the items.
If I was writing a desktop app, where I wouldn't have to create this sub view (ShoppingItemViewModel), my EntityFramework is intelligent enough to check & update all the changes in my database. Unfortunately in this case, I do not understand how this is achievable.
When I was thinking about it I came with the following: Add a new property into the ShoppingItem and ShoppingItemViewModel: public string sCustomKey {get; set; }, which would serve as a unique key for every item. This way, we no longer need to expose our database Id, but we are exposing the 'fake' one.
Second question:
I case my solution would be accurate, what is the best way to update items in the database? The only way I can think of is iterating through all the items in the database and manually check for changes?
Example of what I have in mind:
//IEnumerable<ShoppingItem> would be re-mapped result of ShoppingItemViewModel we have received back from the website
public void UpdateValues(IEnumerable<ShoppingItem> items, string sUserName)
{
//retrieves list of shopping items for specified customer
var allItems = _context.ShoppingUsers
.Include(n => n.Items)
.FirstOrDefault(n => n.UserName == sUserName);
//updates the values
foreach (var sItem in items)
{
var updatedItem = allItems.Items.FirstOrDefault(n => n.Text == sItem.sCustomKey);
if (updatedItem == null)
{
//create new item
var newItem = new ShoppingItem();
newItem.Text = sItem.Text;
newItem.ToRemove = sItem.ToRemove;
allItems.Items.Add(newItem);
}
else
updatedItem.ToRemove = sItem.ToRemove;
}
_context.SaveChanges();
}
But this approach does not seem right to me.
Any help regarding these matters would be more than appreciated as I am still learning how to work with ASP.NET Core and web projects.
In your first question, exposing the item ID in the ViewModels is fine. In your domain layer, you can add validation logic that those ID exists/valid item.
Alternatively, you can use a Guid for your item/product because the ID (int) can easily be predicted.
As far as updating the items, you should not use the "username" as Identifier (of the cart) because that can be predicted/altered by the calling client. You can use Guid either persisted(to Db) or
in-memory. You can add validation as well if this Guid belongs to this username/emailAddress. So updating the items in the cart, consider adding/removing one at a time if that is doable
instead of sending list of items.
I think you have misunderstood something.
Here comes the tricky part (at least for me). From video tutorials I have learned, that I should never (or almost never) expose my real database model to the website (I guess it's for security reasons). Due to that (as visible from my GET method above) I have declared my ShoppingItemViewModel which contains only properties I want to expose to the user (e.g. meaning that Id of my item is not visible).
ViewModel <=> Domain Model <=> ReadModel (Database Model)
The point is that you shouldn't use your ReadModel(Database model) as your ViewModel in Presentation Layer (MVC). All three models will have identity.

How can I issue a SQL Statement against my database and have it create a collection?

I am using EF6 but I don't know if there is any difference between that and earlier versions.
I have the following context:
public IdentityContext()
: base("name=Identity")
{
Database.SetInitializer<IdentityContext>(null);
Configuration.ProxyCreationEnabled = false;
Configuration.LazyLoadingEnabled = false;
Configuration.ValidateOnSaveEnabled = false;
Configuration.AutoDetectChangesEnabled = true;
Database.Log = logInfo => Debug.WriteLine(logInfo);
}
public DbSet<AspNetRole> AspNetRoles { get; set; }
public DbSet<AspNetUserClaim> AspNetUserClaims { get; set; }
public DbSet<AspNetUserLogin> AspNetUserLogins { get; set; }
public DbSet<AspNetUser> AspNetUsers { get; set; }
What I would like to do is to issue a SQL query against this:
I saw one example (not related to my context) which is:
using (var context = new BloggingContext())
{
var blogs = context.Blogs.SqlQuery("SELECT * FROM dbo.Blogs").ToList();
}
But this does not make any sense to me as I cannot see why there is .Blogs after the context.
For my context above can someone explain how I can issue a simple sql statement to get the Id from the AspNetUser table and place these in a collection.
Note that I am using EF6 but in this case I am not sure that is relevant to the question if I query the context. My real needs are for a complex SQL but first I need some suggestion to get me started. Thanks.
If you're using .SqlQuery, you're kind of bypassing the beauty of using LINQ-style lambda expressions to query your database.
You might need to fiddle with the syntax a bit, but something like this should work for your initial requirement of getting user IDs:
var allMyIds = context.AspNetUserLogins.Select(l => l.Id).ToList();
or, if you prefer...
var allMyIds = (from l in context.AspNetUserLogins
select l.Id).ToList();
However, if you really need to execute SQL directly, you can do it on one of the DBSet classes as in your question (in which case the EF makes a valiant attempt at change tracking), or if it's a general query you just want to execute that returns primitive types and isn't specific to any one table, do it against the Database class using ExecuteSqlCommand:
var allMyIds = context.Database.ExecuteSqlCommand("select id from AspNetUserLogins");
Hope that helps!

ASP.NET MVC Entity Framework - Entity Update - Overwriting Database Values with Null Values

I am currently looking for a design pattern or rather a best practice in implementing Repository<Entity>.Update() method for a ASP.NET MVC 4 application which uses Entity Framework 5 with Code First approach.
Problem:
The problem I encountered is that when an entity is queried from the database and shown on a view it may not have all the attributes populated. As a result when the repository.Update(entity) method is invoked, the entity passed to the Update() method may have un-bound properties having null values. However they may have some values in the database. As an example Customer.Misc in below code.
So the problem comes here. According to this approach all the properties which were not bound on the view are set to Null in the database after the first Update() method call.
class Customer
{
public int Id { get; set; }
public string Name { get; set; }
public string Misc { get; set; }
}
[HttpGet]
public ActionResult Update(int id)
{
Repository<Customer> repo = new Repository<Customer>();
return View(repo.GetById(id)); // View only binds Customer.Name
}
[HttpPost]
public ActionResult Update(Customer customer)
{
Repository<Customer> repo = new Repository<Customer>();
repo.Update(customer); // Customer.Misc is null
...
}
public void Update(TEntity entity)
{
var entry = DbContext.Entry<TEntity>(entity);
if (entry.State == EntityState.Detached)
{
ObjectContext.ApplyCurrentValues(EntitySetName, entity);
}
DbContext.SaveChanges();
}
Solutions I could think:
Bind all entity attributes on the view:
I think this is not feasible and at the same time it may lead to performance issues since all attributes get populated.
Implement a custom method to copy property values to avoid null values being copied.
EntityHelper.CopyNotNullValues(source, target) and ignore null values in the source entity. If we do this we might not be able to set any of the values to null if required.
Implement View Models and transform data back and forth with the Domain Model.
This is the best approach I could think of so far. All the attributes bound to the View Model will get populated always, on the Update POST, copy all View Model values to the Domain Model.
Really appreciate your thoughts on this.
In Entity Framework, using ChangeObjectState or ApplyCurrentValues will cause data loss. The only way to work around this issue in this case is attaching the input entity and mark the properties to be updated. See below example:
public void Update(TEntity entity, string[] updatedProperties)
{
DbContext.Entities.Attach(entity);
var entry = DbContext.Entry<TEntity>(entity);
for (int i = 0; i < updatedProperties.Length; i++)
{
entry.SetModifiedProperty(updatedProperties[i]);
}
DbContext.SaveChanges();
}
[HttpPost]
public ActionResult Update(Customer customer)
{
Repository<Customer> repo = new Repository<Customer>();
repo.Update(customer, new string[]{ "Name" }); // Only update name
...
}
It's the best solution I can think of. You wanna have least code and good performance. It's as difficult as finding an easy and well paid job.

Resources