My application is based upon code first entity framework.
I have model called module
public class Module
{
public long Id { get; set; }
public long ModuleTypeId { get; set; }
public ModuleType ModuleType { get; set; }
public string ModuleId { get; set; }
public PropertyConfiguration PropertyConfiguration { get; set; }
public DateTime DateEntered { get; set; }
}
And another Model class called OwnedModule
public class OwnedModule
{
public long Id { get; set; }
public PropertyConfiguration PropertyConfiguration { get; set; }
public long ModuleTypeId { get; set; }
public ModuleType ModuleType { get; set; }
public string ModuleId { get; set; }
public Guid ModuleOwnerId { get; set; }
public Module Module { get; set; }
public DateTime Start { get; set; }
public DateTime? End { get; set; }
}
The idea is that when u want to add new module into system u just add Module class, and OwnedModule is something that has a owner or is owned my someone.
So, basically OwnedModule contains Module and other properties. Here is the OwnedMOduleMap class
public class OwnedModuleMap : EntityTypeConfiguration<OwnedModule>
{
public OwnedModuleMap()
{
Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
HasKey(x => x.Id);
HasOptional(x => x.PropertyConfiguration).WithOptionalPrincipal().WillCascadeOnDelete();
HasRequired(x => x.ModuleType).WithMany().HasForeignKey(x => x.ModuleTypeId);
HasOptional(x => x.Module).WithOptionalDependent();
}
}
If I had to delete Module I would first have to delete it from OwnedModules table and then delete it from Modules table. IF it has a owner that is.
In my repository this is what I've done:
public void DeleteModule(long id)
{
var module = _dbSis.Modules.FirstOrDefault(t=>t.Id==id);
DeleteOwnedModule(module.ModuleId);
_dbSis.Entry(module).State = EntityState.Deleted;
_dbSis.SaveChanges();
}
public long GetOwnedModuleId(string moduleId)
{
var ownedModule= _dbSis.OwnedModules.FirstOrDefault(t => t.ModuleId == moduleId);
if (ownedModule != null)
{
return ownedModule.Id;
}
return 0;
}
public void DeleteOwnedModule(string moduleId)
{
var ownedModuleId = GetOwnedModuleId(moduleId);
var ownedModule = new OwnedModule
{
Id = ownedModuleId
};
_dbSis.Entry(ownedModule).State = EntityState.Deleted;
_dbSis.SaveChanges();
}
But right now my DeleteOwnedModule method is not working, I get error saying, why is this happening? What do i need to make my Delete statement work?
An object with the same key already exists in the ObjectStateManager. The ObjectStateManager cannot track multiple objects with the same key.
PS: if i were not to set the owner while adding a Module, then there is no problem while deleting it.
public void DeleteModule(long id)
{
var module = _dbSis.Modules.FirstOrDefault(t=>t.Id==id);
//DeleteOwnedModule(module.ModuleId);
_dbSis.Entry(module).State = EntityState.Deleted;
_dbSis.SaveChanges();
}
this works perfectly, if I were to delete it manually, then I can open database delete the module I want from OwnedModules table first then from Modules table. This works too but deleting from the method in repopsitory is not working
The problem is this method:
public void DeleteOwnedModule(string moduleId)
{
var ownedModuleId = GetOwnedModuleId(moduleId);
var ownedModule = new OwnedModule
{
Id = ownedModuleId
};
_dbSis.Entry(ownedModule).State = EntityState.Deleted;
_dbSis.SaveChanges();
}
You are creating a new OwnedModule with the id of an existing one. What you need to do is Find the existing module and set that instances state to Deleted (as you do for Module in the method DeleteModule)
public void DeleteOwnedModule(long id)
{
var ownedModule = _dbSis.OwnedModules.FirstOrDefault(t=>t.Id==id);
_dbSis.Entry(ownedModule).State = EntityState.Deleted;
_dbSis.SaveChanges();
}
Incidentally you have a lot of calls to SaveChanges(). Once you get all your code working you may want to consider reducing the number of calls to SaveChanges().
Related
I get this error (An exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll but was not handled in user code
The entity type tblMessage is not part of the model for the current context.) and have tried fixes I found online but they didnt seem to help. I also did somethin similar for another database tabel earlier in the code.
Im trying to retrieve messages form my database table called tblMessages.
Constructor:
public JsonResult ConversationWithContact(int contact)
{
if (Session["UserID"] == null)
{
return Json(new {status = "error", message = "User is not logged in"});
}
//var currentUser = (Models.tblUser)Session["UserID"];
var conversations = new List<Models.tblMessage>();
using (var db = new Models.ChatContext())
{
int currentUserId = (int)Session["UserID"];
var currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);
conversations = db.Conversations.Where(c => (c.receiverId == currentUser.Id
&& c.senderId == contact) ||
(c.receiverId == contact
&& c.senderId == currentUser.Id))
.OrderBy(c => c.created_at)
.ToList();
}
return Json(
new {status = "success", data = conversations},
JsonRequestBehavior.AllowGet
);
}
Context:
public ChatContext() : base("TrinityEntities")
{
}
public static ChatContext Create()
{
return new ChatContext();
}
public DbSet<tblUser> Users { get; set; }
public DbSet<tblMessage> Conversations { get; set; }
Database model class:
public class tblMessage
{
public tblMessage()
{
status = messageStatus.Sent;
}
public enum messageStatus
{
Sent,
Delivered
}
public int Id { get; set; }
public int senderId { get; set; }
public int receiverId { get; set; }
public string message { get; set; }
public messageStatus status { get; set; }
public System.DateTime created_at { get; set; }
}
Here is issue with Table Mapping to database. each entity will be set up to map to a table with the same name as the DbSet<TEntity> property that exposes to the derived context. If no DbSet<TEntity> is included for the given entity, the class name is used.
as you set in your code Users and Conversations is not table name. for that you can customize also refere https://learn.microsoft.com/en-us/ef/core/modeling/relational/tables
and use Data Annotations for specify table name.
public messageStatus status { get; set; }
i think this property is not not part of your table column so you have to specify [NotMapped] Data Annotations.
after changes and adding Data Annotations to table context and table look likes.
public class ChatContext : DbContext
{
public ChatContext()
{
}
public virtual DbSet<tblUser> Users { get; set; }
public virtual DbSet<tblMessage> Conversations { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=test;Trusted_Connection=True;MultipleActiveResultSets=true");
}
}
}
and your models(tables) entities look like.
[Table("tblMessage")]
public class tblMessage
{
public tblMessage()
{
status = messageStatus.Sent;
}
public enum messageStatus
{
Sent,
Delivered
}
public int Id { get; set; }
public int senderId { get; set; }
public int receiverId { get; set; }
public string message { get; set; }
[NotMapped]
public messageStatus status { get; set; }
public System.DateTime created_at { get; set; }
}
[Table("tblUser")]
public class tblUser
{
public int id { get; set; }
public string name { get; set; }
}
now you can access your Conversations and Users after adding [Table("<table-name>")] Data-Annotations.
also you can use Fluent API for table mapping.
after using table mapping table after debug code image like.
i hope it helps you and let me know if require any more information. :)
I need to create a generic way to add missing languages entries to all entities in which implements an specific interface. I found out how to get my collection property, but I still don't know how to add new values on it before proceed to save.
Following a piece of my public override int SaveChanges() handling.
foreach (var translationEntity in ChangeTracker.Entries(<ITranslation>))
{
if (translationEntity.State == EntityState.Added)
{
var translationEntries = translationEntity.Entity.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance)
.Where(x => x.CanWrite &&
x.GetGetMethod().IsVirtual &&
x.PropertyType.IsGenericType == true &&
typeof(IEnumerable<ILanguage>).IsAssignableFrom(x.PropertyType) == true);
foreach (var translationEntry in translationEntries)
{
//Add missing items.
}
}
}
Classes code samples
public partial class FileType : ITranslation
{
public long FileTypeId { get; set; }
public string AcceptType { get; set; }
public virtual ICollection<FileTypeTranslation> FileTypeTranslations { get; set; }
public FileType()
{
this.FileTypeTranslations = new HashSet<FileTypeTranslation>();
}
}
public class FileTypeTranslation : EntityTranslation<long, FileType>, ILanguage
{
[Required]
public string TypeName { get; set; }
}
public partial class ElementType : ITranslation
{
public long ElementTypeId { get; set; }
public string Code { get; set; }
public virtual ICollection<ElementTypeTranslation> ElementTypeTranslations { get; set; }
public ElementType()
{
this.ElementTypeTranslations = new HashSet<FileTypeTranslation>();
}
}
public class ElementTypeTranslation : EntityTranslation<long, ElementType>, ILanguage
{
[Required]
public string Description { get; set; }
}
Entries from ChangeTracker have property called Entity which holds original entity
foreach (var fileType in ChangeTracker.Entries(<FileType>))
{
fileType.Entity.FileTypeTranslations.Add();
}
and for ElementType:
foreach (var elementType in ChangeTracker.Entries(<ElementType>))
{
elementType.Entity.ElementTypeTranslations.Add();
}
I didn't test, but it was too long to paste in comment.
how do I insert data in many to many relationship?
I have these two models definded by this code
public class Article
{
public int ArticleID { get; set; }
public string Title { get; set; }
public DateTime Date { get; set; }
public string Anotation { get; set; }
public string Body { get; set; }
public virtual ICollection<ArticleTag> ArticleTags { get; set; }
}
public class ArticleTag
{
public int ArticleTagID { get; set; }
public string TagName { get; set; }
public virtual ICollection<Article> Articles { get; set; }
}
Now the big Q is how to seed the database with test data. I have some experience with normal tables and queries and in MVC EF I am quite a novice. Normally I would create an association table and in it define the link between these models. But I have read many tutorials and none gave me a deterministic way how to do it, so I you can imagine my confusion.
As I said before, I "created" an assoc table via ModelBuilder and that's where I end :(
public class DatabaseContext : DbContext
{
public DbSet<Article> Articles { get; set; }
public DbSet<ArticleTag> ArticleTags { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Article>().
HasMany(at => at.ArticleTags).WithMany(a => a.Articles).
Map(m => m.MapLeftKey("ArticleID").MapRightKey("ArticleTagID").ToTable("Articles_To_ArticleTags"));
}
}
I need to know the easiest way to seed my DB (don't care if have to delete the assoc table) and understand how it works in the MVC - linking the two models, linking two specific instances, ... , and how to code it all.
Thx for any answer.
So finally solved!
Found a good post here and with this one together I made it work.
In short what I had to do:
Remove my builder link - EF itself creates link (own assoc table)
A little modify models
Create DatabaseInitializer
In the Global.asax to the method Application_Start() add Database.SetInitializer(new DatabaseInitializer()); declaration
don't forget to se ConnectionString and DBcontext
Normally use in a View
Modifications in constructor (not sure if absolutely necessary, maybe it does the same thing as native/default constructor):
public class Article
{
public int ArticleID { get; set; }
public string Title { get; set; }
public DateTime Date { get; set; }
public string Anotation { get; set; }
public string Body { get; set; }
public string SourceLink { get; set; }
public virtual List<ArticleTag> ArticleTags { get; set; }
public Article()
{
ArticleTags = new List<ArticleTag>();
}
}
public class ArticleTag
{
public int ArticleTagID { get; set; }
public string TagName { get; set; }
public virtual List<Article> Articles { get; set; }
public ArticleTag()
{
Articles = new List<Article>();
}
}
And the DatabaseInitializer
public class DatabaseInitializer : DropCreateDatabaseIfModelChanges<DatabaseContext>
{
protected override void Seed(DatabaseContext context)
{
ArticleTag tag1= new ArticleTag { TagName = "aaaa" };
ArticleTag tag2= new ArticleTag { TagName = "bbbb" };
ArticleTag tag3= new ArticleTag { TagName = "cccc" };
var articleTags = new List<ArticleTag> { tag1, tag2, tag3};
articleTags.ForEach(i => context.ArticleTags.Add(i));
context.SaveChanges();
Article a1 = new Article
{
Title = "Title1",
Date = DateTime.Now,
Anotation = "Anotation1",
Body = "article_1",
ArticleTags = new List<ArticleTag> { tag1 }
};
Article a2 = new Article
{
Title = "Title12",
Date = DateTime.Now,
Anotation = "Anotation2",
Body = "article_2",
ArticleTags = new List<ArticleTag> { tag2, tag3 }
};
var articles = new List<Article> { a1, a2 };
articles.ForEach(a => context.Articles.Add(a));
context.SaveChanges();
}
}
I have an ASP.NET MVC application which uses Entity Framework to get data.
I need to transform Entites to Models before passing them to View. Projections can be very complex, but to keep it simple:
public static IQueryable<UserModel> ToModel(this IQueryable<User> users)
{
return from user in users
select new UserModel
{
Name = user.Name,
Email = user.Email,
};
}
This can be used in a controller like this:
return View(Repository.Users.ToModel().ToList());
Very good. But what if I want to use this projection inside another one? Example:
public static IQueryable<BlogPostModel> ToModel(this IQueryable<BlogPost> blogs)
{
return from blogs in blogs
select new BlogPostModel
{
Title = blog.Title,
Authors = blog.Authors.AsQueryable().ToModel(), // (entities are POCOs)
// This does not work, because EF does not understand method ToModel().
};
}
(let's suppose blog can have more then one author and it is of type User).
Can I somehow separate the projections and reuse them inside another ones?
Here's something that actually works (in a simple test application) to only select the requested fields:
namespace Entities
{
public class BlogPost
{
public virtual int Id { get; set; }
public virtual string Title { get; set; }
public virtual DateTime Created { get; set; }
public virtual ICollection<User> Authors { get; set; }
}
public class User
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual string Email { get; set; }
public virtual byte[] Password { get; set; }
public virtual ICollection<BlogPost> BlogPosts { get; set; }
}
}
namespace Models
{
public class BlogPostModel
{
public string Title { get; set; }
public IEnumerable<UserModel> Authors { get; set; }
}
public class UserModel
{
public string Name { get; set; }
public string Email { get; set; }
}
public static class BlogPostModelExtensions
{
public static readonly Expression<Func<BlogPost, BlogPostModel>> ToModelConverterExpression =
p =>
new BlogPostModel
{
Title = p.Title,
Authors = p.Authors.AsQueryable().Select(UserModelExtensions.ToModelConverterExpression),
};
public static readonly Func<BlogPost, BlogPostModel> ToModelConverterFunction = ToModelConverterExpression.Compile();
public static IQueryable<BlogPostModel> ToModel(this IQueryable<BlogPost> blogPosts)
{
return blogPosts.Select(ToModelConverterExpression);
}
public static IEnumerable<BlogPostModel> ToModel(this IEnumerable<BlogPost> blogPosts)
{
return blogPosts.Select(ToModelConverterFunction);
}
}
public static class UserModelExtensions
{
public static readonly Expression<Func<User, UserModel>> ToModelConverterExpression =
u =>
new UserModel
{
Name = u.Name,
Email = u.Email,
};
public static readonly Func<User, UserModel> ToModelConverterFunction = ToModelConverterExpression.Compile();
public static IQueryable<UserModel> ToModel(this IQueryable<User> users)
{
return users.Select(ToModelConverterExpression);
}
public static IEnumerable<UserModel> ToModel(this IEnumerable<User> users)
{
return users.Select(ToModelConverterFunction);
}
}
}
To test it without actually creating a database:
var blogPostsQuery = (
from p in context.BlogPosts
where p.Title.StartsWith("a")
select p).ToModel();
Console.WriteLine(((ObjectQuery)blogPostQuery).ToTraceString());
I'm trying out Entity Framework Code first CTP4. Suppose I have:
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
}
public class Child
{
public int Id { get; set; }
public string Name { get; set; }
public Parent Mother { get; set; }
}
public class TestContext : DbContext
{
public DbSet<Parent> Parents { get; set; }
public DbSet<Child> Children { get; set; }
}
public class ChildEdit
{
public int Id { get; set; }
public string Name { get; set; }
public int MotherId { get; set; }
}
Mapper.CreateMap<Child, ChildEdit>();
Mapping to the Edit model is not a problem. On my screen I select the mother through some control (dropdownlist, autocompleter, etc) and the Id of the mother gets posted in back:
[HttpPost]
public ActionResult Edit(ChildEdit posted)
{
var repo = new TestContext();
var mapped = Mapper.Map<ChildEdit, Child>(posted); // <------- ???????
}
How should I solve the last mapping? I don't want to put Mother_Id in the Child object. For now I use this solution, but I hope it can be solved in Automapper.
Mapper.CreateMap<ChildEdit, Child>()
.ForMember(i => i.Mother, opt => opt.Ignore());
var mapped = Mapper.Map<ChildEdit, Child>(posted);
mapped.Mother = repo.Parents.Find(posted.MotherId);
EDIT
This works, but now I have to do that for each foreign key (BTW: context would be injected in final solution):
Mapper.CreateMap<ChildEdit, Child>();
.ForMember(i => i.Mother,
opt => opt.MapFrom(o =>
new TestContext().Parents.Find(o.MotherId)
)
);
What I'd really like would be:
Mapper.CreateMap<int, Parent>()
.ForMember(i => i,
opt => opt.MapFrom(o => new TestContext().Parents.Find(o))
);
Mapper.CreateMap<ChildEdit, Child>();
Is that possible with Automapper?
First, I'll assume that you have a repository interface like IRepository<T>
Afterwards create the following class:
public class EntityConverter<T> : ITypeConverter<int, T>
{
private readonly IRepository<T> _repository;
public EntityConverter(IRepository<T> repository)
{
_repository = repository;
}
public T Convert(ResolutionContext context)
{
return _repository.Find(System.Convert.ToInt32(context.SourceValue));
}
}
Basically this class will be used to do all the conversion between an int and a domain entity. It uses the "Id" of the entity to load it from the Repository. The IRepository will be injected into the converter using an IoC container, but more and that later.
Let's configure the AutoMapper mapping using:
Mapper.CreateMap<int, Mother>().ConvertUsing<EntityConverter<Mother>>();
I suggest creating this "generic" mapping instead so that if you have other references to "Mother" on other classes they're mapped automatically without extra-effort.
Regarding the Dependency Injection for the IRepository, if you're using Castle Windsor, the AutoMapper configuration should also have:
IWindsorContainer container = CreateContainer();
Mapper.Initialize(map => map.ConstructServicesUsing(container.Resolve));
I've used this approach and it works quite well.
Here's how I did it: (using ValueInjecter)
I made the requirements a little bigger just to show how it works
[TestFixture]
public class JohnLandheer
{
[Test]
public void Test()
{
var child = new Child
{
Id = 1,
Name = "John",
Mother = new Parent { Id = 3 },
Father = new Parent { Id = 9 },
Brother = new Child { Id = 5 },
Sister = new Child { Id = 7 }
};
var childEdit = new ChildEdit();
childEdit.InjectFrom(child)
.InjectFrom<EntityToInt>(child);
Assert.AreEqual(1, childEdit.Id);
Assert.AreEqual("John", childEdit.Name);
Assert.AreEqual(3, childEdit.MotherId);
Assert.AreEqual(9, childEdit.FatherId);
Assert.AreEqual(5, childEdit.BrotherId);
Assert.AreEqual(7, childEdit.SisterId);
Assert.AreEqual(0, childEdit.Sister2Id);
var c = new Child();
c.InjectFrom(childEdit)
.InjectFrom<IntToEntity>(childEdit);
Assert.AreEqual(1, c.Id);
Assert.AreEqual("John", c.Name);
Assert.AreEqual(3, c.Mother.Id);
Assert.AreEqual(9, c.Father.Id);
Assert.AreEqual(5, c.Brother.Id);
Assert.AreEqual(7, c.Sister.Id);
Assert.AreEqual(null, c.Sister2);
}
public class Entity
{
public int Id { get; set; }
}
public class Parent : Entity
{
public string Name { get; set; }
}
public class Child : Entity
{
public string Name { get; set; }
public Parent Mother { get; set; }
public Parent Father { get; set; }
public Child Brother { get; set; }
public Child Sister { get; set; }
public Child Sister2 { get; set; }
}
public class ChildEdit
{
public int Id { get; set; }
public string Name { get; set; }
public int MotherId { get; set; }
public int FatherId { get; set; }
public int BrotherId { get; set; }
public int SisterId { get; set; }
public int Sister2Id { get; set; }
}
public class EntityToInt : LoopValueInjection
{
protected override bool TypesMatch(Type sourceType, Type targetType)
{
return sourceType.IsSubclassOf(typeof(Entity)) && targetType == typeof(int);
}
protected override string TargetPropName(string sourcePropName)
{
return sourcePropName + "Id";
}
protected override bool AllowSetValue(object value)
{
return value != null;
}
protected override object SetValue(object sourcePropertyValue)
{
return (sourcePropertyValue as Entity).Id;
}
}
public class IntToEntity : LoopValueInjection
{
protected override bool TypesMatch(Type sourceType, Type targetType)
{
return sourceType == typeof(int) && targetType.IsSubclassOf(typeof(Entity));
}
protected override string TargetPropName(string sourcePropName)
{
return sourcePropName.RemoveSuffix("Id");
}
protected override bool AllowSetValue(object value)
{
return (int)value > 0;
}
protected override object SetValue(object sourcePropertyValue)
{
// you could as well do repoType = IoC.Resolve(typeof(IRepo<>).MakeGenericType(TargetPropType))
var repoType = typeof (Repo<>).MakeGenericType(TargetPropType);
var repo = Activator.CreateInstance(repoType);
return repoType.GetMethod("Get").Invoke(repo, new[] {sourcePropertyValue});
}
}
class Repo<T> : IRepo<T> where T : Entity, new()
{
public T Get(int id)
{
return new T{Id = id};
}
}
private interface IRepo<T>
{
T Get(int id);
}
}
It's possible to define the foreign key in EF this way as well:
[ForeignKey("MotherId")]
public virtual Parent Mother { get; set; }
public int MotherId { get; set; }
In this case, It's not necessary to do an extra query to find the Mother. Just Assign the ViewModel's MotherId to the Model's MotherId.