I'd like to create an entity that keeps a reference to a clone of itself, and that clone would actually be serialised to json before saving to database.
public class Foo
{
public string StringProperty { get; set; }
public int IntProperty { get; set; }
public Foo Snapshot { get; set; }
}
public class FooConfiguration : IEntityTypeConfiguration< Foo >
{
public virtual void Configure( EntityTypeBuilder< Foo > builder )
{
builder.Property( e => e.StringProperty );
builder.Property( e => e.IntProperty )
.IsRequired();
builder.Property( e => e.Snapshot )
.HasConversion( new FooToJsonConverter() );
}
}
The problem is that because EF knows about Foo (it is referenced in the context and there is a fluent configuration file for it), it creates a foreign key.
Even when I try to ignore it with
builder.Ignore( e => e.Snapshot )
I have successfully serialised another type with a custom converter, but that other type is unknown to EF (no reference in the context and no fluent configuration file).
Is there a way to achieve this?
The problem is that because EF knows about Foo (it is referenced in the context and there is a fluent configuration file for it), it creates a foreign key.
You can create special type - wrapper - EF will not know about.
public class SnapshotWrapper<T>
{
public T? Snapshot { get; set; }
public string Serialize() => JsonSerializer.Serialize(Snapshot);
public static SnapshotWrapper<T> CreateFromJson(string json)
{
if (json == null)
throw new ArgumentNullException(nameof(json));
return new SnapshotWrapper<T>
{
Snapshot = JsonSerializer.Deserialize<T>(json)
};
}
}
Then define interface to identify entities with snapshots:
public interface IHasSnapshot<T>
{
SnapshotWrapper<T> Snapshot { get; }
}
Example for Foo:
public class Foo : IHasSnapshot<Foo>
{
public Foo(int id, string name, int age) : this()
{
FooId = id;
FooName = name ?? throw new ArgumentNullException(nameof(name));
FooAge = age;
}
//to follow DRY principle
//you can specify some SnapshotBase base type for doing this
public Foo()
{
Snapshot = new SnapshotWrapper<Foo>
{
Snapshot = this
};
}
public int FooId { get; set; }
public string? FooName { get; set; }
public int FooAge { get; set; }
[JsonIgnore]
public SnapshotWrapper<Foo> Snapshot { get; set; }
}
Moreover, you can else specify some base EntityTypeConfiguration for such entities:
public abstract class WithSnapshotEntityTypeConfigurationBase<T> : IEntityTypeConfiguration<T>
where T : class, IHasSnapshot<T>
{
public virtual void Configure(EntityTypeBuilder<T> builder)
{
builder.Property(x => x.Snapshot).HasConversion(
x => x.Serialize(),
str => SnapshotWrapper<T>.CreateFromJson(str));
}
}
public class FooConfiguration : WithSnapshotEntityTypeConfigurationBase<Foo>
{
public override void Configure(EntityTypeBuilder<Foo> builder)
{
base.Configure(builder);
builder.HasKey(x => x.FooId);
builder.Property(x => x.FooName).IsRequired().HasMaxLength(200);
builder.HasData(
new Foo(1, "John Doe", 30),
new Foo(2, "Jane Smith", 20),
new Foo(3, "Billy The Drunken", 40),
new Foo(4, "James Webb", 60),
new Foo(5, "Old president", 40));
}
}
This works. A couple of downsides:
Need to mark Snapshot property with [JsonIgnore]
No any constraints for T in IHasSnapshot<T>, so you can write other than Foo (class Foo : IHasSnapshot<Bar>), but it is not critical.
Related
I've got a domain model with collection of owned types. When I try to add more than one object in the ownedtyped collection? I get an exception:
System.InvalidOperationException: 'The instance of entity type 'ChildItem' cannot be tracked because another
instance with the key value '{NameId: -2147482647, Id: 0}' is already being
tracked. When replacing owned entities modify the properties without changing
the instance or detach the previous owned entity entry first.'
How can it be solved?
UPDATED
My domain classes:
public class Parent
{
public int Id { get; set; }
public Child Name { get; set; }
public Child ShortName { get; set; }
}
public class Child
{
public List<ChildItem> Items { get; set; }
}
public class ChildItem
{
public string Text { get; set; }
public string Language { get; set; }
}
My DbContext:
public class ApplicationContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Parent>()
.OwnsOne(c => c.Name, d =>
{
d.OwnsMany(c => c.Items, a =>
{
a.HasForeignKey("NameId");
a.Property<int>("Id");
a.HasKey("NameId", "Id");
a.ToTable("ParentNameItems");
})
.ToTable("ParentName");
})
.ToTable("Parent");
modelBuilder.Entity<Parent>()
.OwnsOne(c => c.ShortName, d =>
{
d.OwnsMany(c => c.Items, a =>
{
a.HasForeignKey("NameId");
a.Property<int>("Id");
a.HasKey("NameId", "Id");
a.ToTable("ParentShortNameItems");
})
.ToTable("ParentShortName");
})
.ToTable("Parent");
}
}
Usage:
static void Main(string[] args)
{
var context = new ApplicationContext();
var parent = new Parent()
{
Name = new Child()
{
Items = new List<ChildItem>()
{
new ChildItem() { Text = "First value", Language = "en-en"},
new ChildItem() { Text = "Second value", Language = "en-en"}
}
},
ShortName = new Child()
{
Items = new List<ChildItem>()
{
new ChildItem() { Text = "First short value", Language = "en-en"},
new ChildItem() { Text = "Second short value", Language = "en-en"}
}
}
};
context.Set<Parent>().Add(parent);
context.SaveChanges();
}
Well, first of all you classes don't make sense. If anything it should be
public class Parent
{
public int Id { get; set; }
public List<Child> Children { get; set; }
}
a parent should have many children (or none possibly, empty list maybe?). What about the child's name and id, doesn't he have one of each ? also maybe a ParentId maybe something like
public class Child
{
public virtual List<ChildItem> Items { get; set; } //why virtual? you planning to inherit?
public string Name {get; set; }
public int Id {get; set; }
public int ParentId {get; set; }
}
That looks a little better, I should think. The database should have matching tables. and let's be honest EF (Entity Framework) auto create will do 99% of the work for you, so please use it.
Problem is solved. It was in line
a.HasKey("NameId", "Id");
in OnModelCreating method.
I used an example where was written abount configuring Collections of owned types.
After deleting "NameId" field from Key definition
a.HasKey("Id");
everything works fine now.
I want AutoMapper to map automatically Members like this:
class Model
{
public int ModelId { get; set; }
}
class ModelDto
{
public int Id { get; set; }
}
Here, I would do a
CreateMap<Model, ModelDTO>()
.ForMember(x => x.Id, e => e.MapFrom(x => x.ModelId)
But, how could I make AutoMapper do the mapping automatically? Most of my classes are like that. The Primary key is in the form: ClassName + "Id".
Edit
I've tried with this, but it doesn't work:
class Program
{
static void Main(string[] args)
{
Mapper.Initialize(exp =>
{
exp.CreateMap<User, UserDto>();
exp.ForAllPropertyMaps(map => map.DestinationProperty.Name.Equals("Id"), (map, expression) => expression.MapFrom(map.SourceType.Name + "Id"));
});
var user = new User() { UserId = 34};
var dto = Mapper.Map<UserDto>(user);
}
}
public class UserDto
{
public int Id { get; set; }
}
class User
{
public int UserId { get; set; }
}
Yes, the code looks reasonable, but it doesn't work. That's because it runs after the property maps are computed. And there are none in this case, because the names don't match. My bad :) Try
exp.ForAllMaps((typeMap, mappingExpression) =>
mappingExpression.ForMember("Id", o=>o.MapFrom(typeMap.SourceType.Name + "Id"))
);
Entities:
public class Entity
{
public int Id { get; set; }
}
public class User : Entity
{
public string Name { get; set; }
public Company Company { get; set; }
}
public class Company : Entity
{
public string Name { get; set; }
}
Dto's:
public class EntityDto
{
public int Id { get; set; }
}
public class UserDto : EntityDto
{
public string Name { get; set; }
public int? CompanyId { get; set; }
}
So I want to map User to UserDto like User.Company == null => UserDto.CompanyId == null and vice versa.
That is my Automapper configuration:
Mapper.Initialize(configuration =>
{
configuration
.CreateMap<User, UserDto>()
.ReverseMap();
});
This works fine:
[Fact]
public void UnattachedUserMapTest()
{
// Arrange
var user = new User { Company = null };
// Act
var userDto = Mapper.Map<User, UserDto>(user);
// Assert
userDto.CompanyId.Should().BeNull();
}
but this test fails:
[Fact]
public void UnattachedUserDtoMapTest()
{
// Arrange
var userDto = new UserDto { CompanyId = null };
// Act
var user = Mapper.Map<UserDto, User>(userDto);
// Assert
user.Company.Should().BeNull();
}
Details:
Expected object to be <null>, but found
Company
{
Id = 0
Name = <null>
}
Doesn't work for me:
...
.ReverseMap()
.ForMember(user => user.Company, opt => opt.Condition(dto => dto.CompanyId != null));
and well as that (just for example):
...
.ReverseMap()
.ForMember(user => user.Company, opt => opt.Ignore());
Why does Automapper create nested object and how can I prevent it?
That "suddenly" bit is funny :)
configuration.CreateMap<User, UserDto>().ReverseMap().ForPath(c=>c.Company.Id, o=>o.Ignore());
You have a default MapFrom with CompanyId and that is applied in reverse. For details see this and a few other similar issues.
In the next version (on MyGet at the moment) you'll also be able to use
configuration.CreateMap<User, UserDto>().ReverseMap().ForMember(c=>c.Company, o=>o.Ignore());
In my project I have a base class (not mapped):
public abstract class BaseEntity
{
public virtual string Name { get; set; }
public virtual string Description { get; set; }
}
Also I have a few inherited classes (they look all almost the same, so here is a code and map for only one)
public class User : BaseEntity
{
public virtual int UserId { get; set; }
public virtual string Login { get; set; }
public virtual string PasswordHash { get; set; }
public virtual ISet<BaseEntity> Entities { get; set; }
}
public class UserMap : ClassMap<User>
{
public UserMap()
{
this.Id(x => x.UserId);
this.Map(x => x.Login);
this.Map(x => x.PasswordHash);
this.HasManyToMany<BaseEntity>(x => x.Entities);
}
}
Next, I have a NHibernateHelper:
public class NHibernateHelper
{
public static ISession OpenSession()
{
ISessionFactory sessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ConnectionString(#"someconstring")
.ShowSql()
)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<User>())
.ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(false, true))
.BuildSessionFactory();
return sessionFactory.OpenSession();
}
}
And here is a question:
How can I exclude BaseEntity class from mapping, if I need table like EnitiyToEntity in my Database for many-to-many relationship?
Take a look to this:
https://www.codeproject.com/Articles/232034/Inheritance-mapping-strategies-in-Fluent-Nhibernat
If I understand your question the solution should be to implement TPC (Table per concrete class).
By the way, in your mapping you have to use the concrete type for HasManyToMany.
For example (I supposed your user is referenced to many groups):
HasManyToMany<Group>(x => x.Entities).Table("UsersGroups");
where the Group class is something like this:
public class Group : BaseEntity
{
public virtual int GroupId { get; set; }
public virtual string PasswordHash { get; set; }
public virtual ISet<BaseEntity> Members { get; set; }
}
And in the GroupMap class you can reference the users like this:
HasManyToMany<User>(x => x.Members).Table("UsersGroups");
If you reference a class you have to map it. So map Entity as ClassMap and all the others as SubclassMap. They will end up as union subclass which is one table per class. Unfortunatly you can not map a hasmanytoany with FNH.
You can map it as hasmanytomany and work around it:
var config = new Configuration();
config.BeforeBindMapping += BeforeBindMapping;
_config = Fluently
.Configure(config)
...
private void BeforeBindMapping(object sender, NHCfg.BindMappingEventArgs e)
{
var userclass = e.Mapping.RootClasses.FirstOrDefault(rc => rc.name.StartsWith(typeof(User).FullName));
if (userclass != null)
{
HbmSet prop = (HbmSet)paymentclass.Properties.FirstOrDefault(rc => rc.Name == "Entities");
prop.Item = new HbmManyToAny // == prop.ElementRelationship
{
column = new[]
{
new HbmColumn { name = "entityType", notnull = true, notnullSpecified = true },
new HbmColumn { name = "entity_id", notnull = true, notnullSpecified = true }
},
idtype = "Int64",
metatype = "String",
metavalue = typeof(Entity).Assembly.GetTypes()
.Where(t => !t.IsInterface && !t.IsAbstract && typeof(Entity).IsAssignableFrom(t))
.Select(t => new HbmMetaValue { #class = t.AssemblyQualifiedName, value = t.Name })
.ToArray()
};
}
}
I have introduced a many to many relationship between two of my existing tables. For this, I have added a third table, which contains only the Ids of the other two tables.
Since I am using EF, I have also added
public virtual List<EntityOne> EntityOnes in EntityTwo
and
public virtual List<EntityTwo> EntityTwos in EntityOne.
However, with this, when I get the EntityTwo object, it does not contain the associated EntityOne object. The list has a count of zero, even though the data is there in the tables.
Am I missing something here? Is there anything else, I need to do?
Not sure,if this is relevant, but I have also this in OnModelCreation
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<EntityOne>().
HasMany(p => p.EntityTwos).
WithMany(a => a.EntityOnes).
Map(
m =>
{
m.MapLeftKey("EntityTwoId");
m.MapRightKey("EntityOneId");
m.ToTable("EntityRelations");
});
////Make sure a context is not created by default.
}
Try this:
public partial class One
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual int Id { get; set; }
private ICollection<OneTwo> _oneTwos;
public virtual ICollection<OneTwo> OneTwos
{
get { return _oneTwos ?? (_oneTwos = new List<OneTwo>()); }
set { _oneTwos = value; }
}
}
public partial class Two
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public virtual int Id { get; set; }
private ICollection<OneTwo> _oneTwos;
public virtual ICollection<OneTwo> OneTwos
{
get { return _oneTwos ?? (_oneTwos = new List<OneTwo>()); }
set { _oneTwos = value; }
}
}
Add navigation properties to the join class:
public partial class OneTwo
{
public virtual int OneId { get; set; }
public virtual int TwoId { get; set; }
public virtual One One { get; set; }
public virtual Two Two { get; set; }
}
Add composite key to the join class and configure relationships:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<OneTwo>() // composite primary key
.HasKey(p => new { p.OneId, p.TwoId });
modelBuilder.Entity<OneTwo>()
.HasRequired(a => a.One)
.WithMany(c => c.OneTwos)
.HasForeignKey(fk => fk.OneId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<OneTwo>()
.HasRequired(a => a.Two)
.WithMany(c => c.OneTwos)
.HasForeignKey(fk => fk.TwoId)
.WillCascadeOnDelete(false);
// TODO: handle orphans when last asociation is deleted
}
An alternative strategy is to configure EF relationships via EntityTypeConfiguration<>. The following many-to-many relationship implementation demonstrates that approach:
City.cs
public partial class City
{
public virtual int Id { get; set; }
private ICollection<CountyCity> _countiesCities;
public virtual ICollection<CountyCity> CountiesCities
{
get { return _countiesCities ?? (_countiesCities = new List<CountyCity>()); }
set { _countiesCities = value; }
}
}
County.cs
public partial class County
{
public virtual int Id { get; set; }
private ICollection<CountyCity> _countiesCities;
public virtual ICollection<CountyCity> CountiesCities
{
get { return _countiesCities ?? (_countiesCities = new List<CountyCity>()); }
set { _countiesCities = value; }
}
}
CountyCity.cs
public partial class CountyCity
{
public virtual int CountyId { get; set; }
public virtual int CityId { get; set; }
public virtual County County { get; set; }
public virtual City City { get; set; }
}
CountyCityConfiguration.cs (EF 6 implementation)
public class CountyCityConfiguration : IEntityTypeConfiguration<CountyCity>
{
public void Map(EntityTypeBuilder<CountyCity> builder)
{
// Table and Schema Name declarations are optional
//ToTable("CountyCity", "dbo");
// composite primary key
builder.HasKey(p => new { p.CountyId, p.CityId });
builder.HasOne(pt => pt.County)
.WithMany(p => p.CountiesCities)
.HasForeignKey(pt => pt.CountyId)
.OnDelete(DeleteBehavior.Restrict);
builder.HasOne(pt => pt.City)
.WithMany(t => t.CountiesCities)
.HasForeignKey(pt => pt.CityId)
.OnDelete(DeleteBehavior.Restrict);
// TODO: handle orphans when last association is deleted
}
}
Entity Framework 6 Implementations:
You may configure the composite key and relationships using EntityTypeConfiguration<> as the previous code demonstrates.
Entity Framework Core Implementations:
EntityTypeConfiguration<> has not yet been migrated. However, it is on the roadmap for the next release.
In the meantime, you can employ the temporary pattern suggested by the EF team, or one of the patterns discussed this rather lengthy StackOverflow post discussing entity configuration in Entity Framework 7.
I implemented the pattern posted by Cocowalla in the lengthy discussion prior to reading the EF Team post. The source code for my workaround is available in this GitHub repository.
IEntityTypeConfiguration.cs
namespace Dna.NetCore.Core.DAL.EFCore.Configuration.Temporary.Cocowalla
{
// attribute: https://stackoverflow.com/questions/26957519/ef-7-mapping-entitytypeconfiguration/35373237#35373237
public interface IEntityTypeConfiguration<TEntityType> where TEntityType : class
{
void Map(EntityTypeBuilder<TEntityType> builder);
}
}
Here is my implementation of that pattern:
namespace Dna.NetCore.Core.DAL.EFCore.Configuration.Common
{
public class StateOrProvinceConfiguration : IEntityTypeConfiguration<StateOrProvince>
{
public void Map(EntityTypeBuilder<StateOrProvince> builder)
{
// EF Core
builder.HasOne(p => p.Country).WithMany(p => p.StateOrProvinces).HasForeignKey(s => s.CountryId).OnDelete(DeleteBehavior.Cascade);
builder.HasMany(d => d.Cities).WithOne().OnDelete(DeleteBehavior.Cascade);
builder.HasMany(d => d.Counties).WithOne().OnDelete(DeleteBehavior.Cascade);
}
}
}