entity-framework get entityreference value - entity-framework

I have an entity object which is connected to another entities.
I want to loop through all entity properties , if the property is String then do something with the value.
If the property is EntityReference, I want to get it's value (it has only one), and do something with the value as well.
I was able to determine if the property is string or EntityReference.
I get the String value by -
value = typeof(entity).GetProperty(property.Name).GetValue(request, null);
but how do I get the value of an entityreference ?

Just trace the property tree.
You have the first step. repeat for lower properties.
var TopLevelProp = poco.GetType().GetProperty(property.Name).GetValue(poco, null);
var LowerProp = TopLevelProp.GetType().GetProperty("aLowerPropName").GetValue(TopLevelProp, null);
although you tagged this EF. What did you mean by entity reference ?
edit: in the hope i have covered the entity and its key question
Here is a sample Repository covering EF Context and entity access. See the Entity field and Entity KEY field methods...
public class Repository<T> : IRepositoryEF<T> where T : BaseObject {
public RepositoryEF(DbContext context) { Context = context; }
public DbEntityEntry<T> Entry(T entity) { return Context.Entry(entity); }
public DbSet<T> EntityDbSet() { return Context.Set<T>(); }
public ObjectContext ObjectContext { get { return ((IObjectContextAdapter) this.Context).ObjectContext; } }
public DbContext Context { get; protected set; }
public EntityState GetEntityState(object entity) { return Context.Entry(entity).State; }
public ObjectSet<T> GetObjectSet() { return ObjectContext.CreateObjectSet<T>(); }
public IList<string> GetEntityFields() {
var entityFields = GetObjectSet().EntitySet.ElementType.Properties;
return entityFields.Select(e => e.Name).ToList();
}
public string[] GetEntityKeyFields() { return GetObjectSet().EntitySet.ElementType.KeyMembers.Select(k => k.Name).ToArray(); }
public EntityKey GetEntityKey(T entity) {
if (entity == null) {
return null;
}
return ObjectContext.CreateEntityKey(GetObjectSet().EntitySet.Name, entity);
}
public string GetEntityKeyAsString(T entity) {
if (entity == null) {
return string.Empty;
}
var eK = GetEntityKey(entity);
var keyAsString = eK.EntityKeyValues.Aggregate("", (current, keyField) => current + keyField.Key + "=" + keyField.Value + ",");
return keyAsString;
}
}
If you want to get all the metadata in the Context:
ObjectContext objContext = ((IObjectContextAdapter)context).ObjectContext;
MetadataWorkspace workspace = objContext.MetadataWorkspace;
IEnumerable<EntityType> managedTypes = workspace.GetItems<EntityType>(DataSpace.OSpace);
You can go to town on the meta data. see all enums values in DataSpace to get at various parts of the model

Related

AddOrUpdate violates unique index

I'm writing an MVC app in ASP.NET with the help of EF and I'm trying to seed my database. I have the following model:
public class Team
{
[ScaffoldColumn(false)]
public int Id { get; set; }
[ForeignKey("ParentTeam")]
public int? ParentTeamId { get; set; }
[Required(ErrorMessage = "Cannot create a Team without a name")]
[Index(IsUnique = true)]
[MaxLength(30)]
public string Name { get; set; }
public IEnumerable<string> Members { get; set; }
public virtual Team ParentTeam { get; set; }
public Team() { }
public Team(string name)
{
Name = name;
}
}
My migration says:
var team = new Team("Admin");
var team2 = new Team("Test Team");
var team3 = new Team("Test Team 2");
context.Teams.AddOrUpdate(t => t.Name, team, team2, team3);
context.SaveChanges();
And then, when I run Update-Database, I get:
System.Data.SqlClient.SqlException: Cannot insert duplicate key row in
object 'dbo.Teams' with unique index 'IX_Name'. The duplicate key
value is (Admin).
It's a little confusing - I thought I told AddOrUpdate to identify rows to update by their names, but this does not happen. I cannot add Name to Team's primary key, because it has a self-referencing foreign key (I could add ParentTeamName as a property, but I don't feel that it should be necessary). Am I misunderstanding the behaviour of AddOrUpdate? Did I specify the condition wrong?
I had the exact same reason. In my case, it was working fine, until I needed to use an Unique Index, when it broke.
My solution was to create a CustomAddOrUpdate method where I try to find the existing instance first based on a Where predicate. If I find it, I just update the properties and if not, it is added to the context.
However, before updating the instance, I had to copy the key values from the original instance to the new instance, to avoid an EF exception telling you cannot change key properties.
Here are the code snippets:
1) First the code in the context class
public void CustomAddOrUpdate<TEntity>(Expression<Func<TEntity, bool>> whereExpression, TEntity entity) where TEntity : class
{
var entitySet = this.EntitySet<TEntity>();
var foundInstance = entitySet.Where(whereExpression).FirstOrDefault();
if (foundInstance != null)
{
CopyKeyProperties<TEntity>(foundInstance, entity);
Entry(foundInstance).CurrentValues.SetValues(entity);
}
else
{
entitySet.Add(entity);
}
}
private void CopyKeyProperties<TEntity>(TEntity source, TEntity target) where TEntity : class
{
string[] keys = this.GetKeyNames<TEntity>();
foreach(var keyName in keys)
{
Entry(target).Property(keyName).CurrentValue = Entry(source).Property(keyName).CurrentValue;
}
}
2) Then on my seed code:
var entityList = new List<MyExempleEntity>()
{
new MyExampleEntity { Prop1 = "a p1", Prop2 = "a p2" },
new MyExampleEntity { Prop1 = "b p1", Prop2 = "b p2" },
new MyExampleEntity { Prop1 = "c p1", Prop2 = "c p2" },
}
foreach(var item in entityList)
{
context.CustomAddOrUpdate<MyExampleEntity>(x => x.Prop1 == item.Prop1 && x.Prop2 == item.Prop2, item);
}
context.SaveChanges()
3) And to wrap up, here you are the code to get the KeyProperties from an entity:
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Linq;
namespace System.Data.Entity
{
public static class DbContextExtensions
{
public static string[] GetKeyNames<TEntity>(this DbContext context)
where TEntity : class
{
return context.GetKeyNames(typeof(TEntity));
}
public static string[] GetKeyNames(this DbContext context, Type entityType)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
MetadataWorkspace metadata = ((IObjectContextAdapter)context).ObjectContext.MetadataWorkspace;
// Get the mapping between CLR types and metadata OSpace
var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace));
// Get metadata for given CLR type
var entityMetadata = metadata
.GetItems<EntityType>(DataSpace.OSpace)
.Single(e => objectItemCollection.GetClrType(e) == entityType);
return entityMetadata.KeyProperties.Select(p => p.Name).ToArray();
}
}
}
The above code was grabbed from this blog:
https://romiller.com/2014/10/07/ef6-1-getting-key-properties-for-an-entity/

Breeze EF SaveChanges() on a DTO

I've been struggling with Breeze to SaveChanges to a projection and admit I new to both EF and breeze. There were some similar questions earlier when I was trying to use WCF, but now I have abandoned WCF and added EF directly to my solution.
In my controller I return the DTO for the metadata to breeze along with the DTO and it binds perfectly.
After altering the data on the client my Breese Controllers [HttpPost] SaveChanges(save Bundle) is called and map contains the DTO and the changes.
How Do I persist the Changes? If I re-read the DTO projection for breeze to update then EF cant save a projection because it's not "tracked", if I read the Full entity, then Breeze error with "Sequence contains no matching element" because its looking for the DTO? Am I suppose to use AutoMapper?
Controller:
[BreezeController]
public class BreezeController : ApiController
{
readonly EFContextProvider<ManiDbContext> _contextProvider = new EFContextProvider<ManiDbContext>();
[HttpGet]
public string Metadata()
{
return _contextProvider.Metadata();
}
[HttpGet]
public IQueryable<ConsigneDTO> Consignee(string refname)
{
return _contextProvider.Context.consigneDTO(refname);
}
[HttpPost]
public SaveResult SaveChanges(JObject saveBundle)
{
ManiDbContextProvider _mcontextProvider = new ManiDbContextProvider();
return _mcontextProvider.SaveChanges(saveBundle);
}
ManiDbContext (the main DBContext is CifContext which is Database First/EF Reverse Engineer)
public class ManiDbContext : DbContext
{
public CifContext CifDbContext = new CifContext();
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
Database.SetInitializer<ManiDbContext>(null);
modelBuilder.Configurations.Add(new ConsigneDTOMap());
}
public override int SaveChanges()
{
CifDbContext.SaveChanges();
return 1;
}
public IQueryable<ConsigneDTO> consigneDTO(string refname)
{
IQueryable<ConsigneDTO> q = this.CifDbContext.Consignes
.Where(x => x.Refname == refname)
.Select(f => new ConsigneDTO {Refname = f.Refname, Consignee = f.Consignee, Address1 = f.Address1, Address2 = f.Address2, Address3 = f.Address3});
return q;
}
ManiDbContextProvider
public class ManiDbContextProvider : EFContextProvider<CifContext>
// public class ManiDbContextProvider : EFContextProvider<ManiDbContext>
{
public ManiDbContextProvider() : base() { }
protected override void OpenDbConnection()
{// do nothing
}
protected override void CloseDbConnection()
{ // do nothing
}
protected override bool BeforeSaveEntity(EntityInfo entityInfo)
{
var entity = entityInfo.Entity;
if (entity is ConsigneDTO)
{
return BeforeSaveConsignee(entity as ConsigneDTO, entityInfo);
}
throw new InvalidOperationException("Cannot save entity of unknown type");
}
private bool BeforeSaveConsignee(ConsigneDTO c, EntityInfo info)
{
var consdata = this.Context.CifDbContext.Consignes
.Where(x => x.Refname == c.Refname)
.FirstOrDefault(); // ENTITY
// var consdata = this.Context.consigneDTO(c.Refname); // DTO
return (null != consdata) || throwCannotFindConsignee();
}
CifContext (Full Columns - First/EF Reverse Engineer/ Consigne class contains Keys)
public partial class CifContext : DbContext
{
static CifContext()
{
Database.SetInitializer<CifContext>(null);
}
public CifContext()
: base("Name=CifContext")
{
}
public DbSet<Consigne> Consignes { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); // Use singular table names
Database.SetInitializer<CifContext>(null);
modelBuilder.Configurations.Add(new ConsigneMap());
}
Regardless if I Read the Entity or the DTO - I'm Clueless on how breeze updates EF
Any Help greatly appreciated :)
Regards,
Mike

Handling Related Data when using Entity Framework Code First

I have two Classes: LicenseType and EntityType.
[Table("LicenseType")]
public class LicenseType : ComplianceBase, INotifyPropertyChanged
{
private List<Certification> _certifications = new List<Certification>();
private List<EntityType> _entityTypes = new List<EntityType>();
public List<EntityType> EntityTypes
{
get { return _entityTypes; }
set { _entityTypes = value; }
}
public List<Certification> Certifications
{
get { return _certifications; }
set { _certifications = value; }
}
}
and
[Table("EntityType")]
public class EntityType : ComplianceBase, INotifyPropertyChanged
{
private List<LicenseType> _licenseTypes = new List<LicenseType>();
public List<LicenseType> LicenseTypes
{
get { return _licenseTypes; }
set
{
_licenseTypes = value;
// OnPropertyChanged();
}
}
}
The both derive from ComplianceBase,
public class ComplianceBase
{
private int _id;
private string _name;
private string _description;
public string Description
{
get { return _description; }
set
{
if (_description == value) return;
_description = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
public int Id
{
get { return _id; }
set
{
if (value == _id) return;
_id = value;
OnPropertyChanged();
}
}
public string Name
{
get { return _name; }
set
{
if (value == _name) return;
_name = value;
OnPropertyChanged();
}
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
What I want is to be able to do is associate an EntityType with one or more LicenseTypes, so for instance, an EntityType "Primary Lender" could be associated with say two LicenseTypes, "Lender License" and "Mortgage License". In this situation, I want one record in the EntityType table, "Primary Lender" and two records in my LicenseType table: "Lender License" and "Mortgage License".
The code for adding related LicenseTypes to my EntityType is done by calling:
_currentEntity.LicenseTypes.Add(licenseType);
and then calling _context.SaveChanges();
There is an additional table, "EntityTypeLicenseTypes" that serves as the lookup table to relate these two tables. There are two records to join the EntityType with the two related LicenseTypes.
And this works. However, my code also adds (it duplicates) the LicenseType record and adds it in the LicenseType table for those records that are being associated.
How can I stop this from happening?
In order to avoid the duplication you must attach the licenseType to the context:
_context.LicenseTypes.Attach(licenseType);
_currentEntity.LicenseTypes.Add(licenseType);
_context.SaveChanges();

Updating and Deleting Associated Records in a One-To-Many Relationship using Entity Framework

Using EF 4.1 Code First, I have a Member entity and it in turn has two "one-to-many" relationships for a HomeAddress and WorkAddress. It also has a boolean property to state whether or not to use either of these addresses.
I have two issues that I can't figure out:
Whenever I update a member's address, a new record is added to the MemberAddresses table (with a new ID value) and the existing record is not deleted. Though it looks fine from the front-end perspective as the HomeAddressId and WorkAddressId in the parent Members table is updated with the new record, the old records are kept in the table (orhpaned). I don't want it to add a new address record when the address is updated. I only want it to update the existing record. If it has to add a new one, then I at least want it to clear out the old one.
There are times that I want to delete the address record from the table. For example, if the member previously had an associated HomeAddress and later the DontUseHomeAddress is set to true, I want the address to be deleted from the table. So far, I have tried setting it to null, but that just prevents any updates. It doesn't delete it.
I'm sure there just some code piece I'm missing, so I'm including all the relevant code below that I think might affect this.
public abstract class Entity
{
public int Id { get; set; }
}
public class Member : Entity
{
public string Name { get; set; }
public bool DontUseHomeAddress { get; set; }
public virtual MemberAddress HomeAddress { get; set; }
public bool DontUseWorkAddress { get; set; }
public virtual MemberAddress WorkAddress { get; set; }
//... other properties here ...
}
public class MemberMap : EntityTypeConfiguration<Member>
{
public MemberMap()
{
ToTable("Members");
Property(m => m.Name).IsRequired().HasMaxLength(50);
//TODO: Somehow this is creating new records in the MemberAddress table instead of updating existing ones
HasOptional(m => m.HomeAddress).WithMany().Map(a => a.MapKey("HomeAddressId"));
HasOptional(m => m.WorkAddress).WithMany().Map(a => a.MapKey("WorkAddressId"));
}
}
public class MemberAddressMap : EntityTypeConfiguration<MemberAddress>
{
public MemberAddressMap()
{
ToTable("MemberAddresses");
Property(x => x.StreetAddress).IsRequired().HasMaxLength(255);
Property(x => x.City).IsRequired().HasMaxLength(50);
Property(x => x.State).IsRequired().HasMaxLength(2);
Property(x => x.ZipCode).IsRequired().HasMaxLength(5);
}
}
Here is the InsertOrUpdate method from my repository class that my controller calls:
public class Repository<TEntity> : IRepository<TEntity> where TEntity : Entity
{
private readonly EfDbContext _context;
private readonly DbSet<TEntity> _dbSet;
public Repository(EfDbContext context)
{
_context = context;
_dbSet = _context.Set<TEntity>();
}
public bool InsertOrUpdate(TEntity entity)
{
if(entity.Id == 0)
{
_dbSet.Add(entity);
}
else
{
_context.Entry(entity).State = EntityState.Modified;
}
_context.SaveChanges();
return true;
}
//... Other repository methods here ...
}
EDIT: Adding in code for UnitOfWork and MemberServices
public class MemberServices : IMemberServices
{
private readonly IUnitOfWork _unitOfWork;
private readonly IRepository _memberRepository;
public MemberServices(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
_memberRepository = unitOfWork.RepositoryFor<Member>();
}
public Member Find(int id)
{
return _memberRepository.FindById(id);
}
public bool InsertOrUpdate(Member member)
{
// if(member.HomeAddress != null)
// _unitOfWork.SetContextState(member.HomeAddress, EntityState.Modified);
//
// if(member.WorkAddress != null)
// _unitOfWork.SetContextState(member.WorkAddress, EntityState.Modified);
//
// if(member.DontUseHomeAddress)
// {
// //TODO: This is an attempted hack... fix it by moving somewhere (possibly to repository)
// var context = new EfDbContext();
// context.Set<MemberAddress>().Remove(member.HomeAddress);
// context.SaveChanges();
// }
_memberRepository.InsertOrUpdate(member);
return true;
}
}
public class UnitOfWork : IUnitOfWork
{
private readonly EfDbContext _context;
public UnitOfWork()
{
_context = new EfDbContext();
}
public IRepository<T> RepositoryFor<T>() where T : Entity
{
return new Repository<T>(_context);
}
public void Attach(Entity entity)
{
_context.Entry(entity).State = EntityState.Unchanged;
}
public void SetContextState(Entity entity, EntityState state)
{
_context.Entry(entity).State = state;
}
public void Save()
{
_context.SaveChanges();
}
}
Setting the state _context.Entry(entity).State = EntityState.Modified; doesn't affect the state of related entities. If you want to take care of changes of your related entities you must set their state to Modified as well:
if (member.HomeAddress != null)
_context.Entry(member.HomeAddress).State = EntityState.Modified;
if (member.WorkAddress != null)
_context.Entry(member.WorkAddress).State = EntityState.Modified;
_context.Entry(member).State = EntityState.Modified;
This is not generic anymore.
To delete an entity you have to call the appropriate method to delete an entity; setting the navigation property to null is not enough:
_context.MemberAddresses.Remove(member.HomeAddress);

Entity Framework Generic Repository

I am writing a generic repository to be used for my every model CRUD operation using entity framework CTP5 as following:
public class BaseRepository<TEntity> : IRepository<TEntity> where TEntity : BaseEntity
{
public DbContext Context { get; set; }
public void Insert(TEntity entity)
{
if (Context.Entry<TEntity>(entity).State == EntityState.Detached)
{
Context.Set<TEntity>().Attach(entity);
}
Context.Set<TEntity>().Add(entity);
Context.SaveChanges();
}
public void Delete(int id)
{
TEntity entity = Context.Set<TEntity>().Find(id);
if (Context.Entry<TEntity>(entity).State == EntityState.Detached)
{
Context.Set<TEntity>().Attach(entity);
}
Context.Set<TEntity>().Remove(entity);
Context.SaveChanges();
}
public void Delete(TEntity entity)
{
Context.Set<TEntity>().Remove(entity);
Context.SaveChanges();
}
public void Update(TEntity entity)
{
TEntity status = Context.Set<TEntity>().Find(entity.Id);
status = entity;
Context.SaveChanges();
}
public TEntity GetFirst()
{
var entity = Context.Set<TEntity>().FirstOrDefault();
if (entity == null) return null;
return entity;
}
public TEntity GetNext(int id)
{
var entity = (from u in Context.Set<TEntity>()
where u.Id > id
select u).FirstOrDefault();
if (entity == null) return null;
return entity;
}
public TEntity GetPrevoius(int id)
{
var entity = (from u in Context.Set<TEntity>()
where u.Id < id
orderby u.Id descending
select u).FirstOrDefault();
if (entity == null) return GetFirst();
return entity;
}
public TEntity GetLast()
{
var entity = (Context.Set<TEntity>().OrderByDescending(u => u.Id)).FirstOrDefault();
if (entity == null) return null;
return entity;
}
public TEntity GetById(int id)
{
return Context.Set<TEntity>().Find(id);
}
public int GetMaxId()
{
var max = Context.Set<TEntity>().Count()+ 1;
return max;
}
}
everything works fine but Update method which nither doesnt generate any error nor save any changes back to database.
Can anybody guid me how to solve this issue?
You can use CurrentValues.SetValues:
public void Update(TEntity entity)
{
TEntity status = Context.Set<TEntity>().Find(entity.Id);
Context.Entry(status).CurrentValues.SetValues(entity);
Context.SaveChanges();
}
It updates scalar and complex properties but not navigation properties.
You're overwriting the variable status with a totally new object, taking the one from the database out of scope, but not actually modifying the object that is attached to the context, which is what you'll want to do.
The only way I can think off the top of my head is to use reflection to read all the properties of the type, and assign the values to the original object based on the new one, something like:
foreach (var prop in typeof(TEntity).GetProperties())
{
prop.SetValue(status, prop.GetValue(entity, null), null);
}