Entity-framework 6.1 querystring and ObjectContext - entity-framework-5

I am new to Entity-framework and MVC and I am trying to make a Data Access Layer (separate layer). I am using VS 2013, Entity-framework 6.1.3 and MVC5. So far I have created Connection Helper class to connect to the database, but I need a little help here.
IConnectionHelper.cs
public interface IConnectionHelper
{
string ConnectionString { get; }
ObjectContext Connection { get; }
}
ConnectionHelper.cs
public class ConnectionHelper : IConnectionHelper
{
public string ConnectionString
{
get {
return ConfigurationManager.ConnectionStrings["databaseEntities"].ToString();
}
}
private ObjectContext _connection;
public ObjectContext Connection
{
get {
//Need Help what to do here!
}
}
}
I just want to learn how to pass connection string name to its constructor.
Can you guys please help me, Thanks

Related

ASP.NET using UrlHelper in ViewModel

I'm trying to strongly type (such as it is) some URLs for a web app when I build a viewmodel.
So I have something like:
new MyModel {
Text = "Foo",
Url = new UrlHelper(Request.RequestContext).Action("MyAction")
}
This works just fine in a controller method, but I have another situation where I am not receiving the Request.Context because it's being called in another class.
Is there another way to do this so that I'm not using "magic strings" and/or relying on the context object?
Use Reference
HttpContext.Current
which is derived from system.web. There for following code will work anywhere in your application.
UrlHelper objUrlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
objUrlHelper.Action("About");
Example:
public class MyViewModel
{
public int ID { get; private set; }
public string Link
{
get
{
UrlHelper objUrlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
return objUrlHelper.Action("YourAction", "YourController", new { id = this.ID });
}
}
public MyViewModel(int id)
{
this.ID = id;
}
}

Unable to cast System.Security.Principal.WindowsPrincipal CustomPrincipal in MVC5

I am trying to implement a custom principal in an MVC5 app. To start I have tried to just implement IPrincipal and also override the base WebViewPage. However, the cast from to the customPrincipal is not working. I am getting :
Unable to cast object of type 'System.Security.Principal.WindowsPrincipal' to type
CustomPrincipal.
I cannot understand why this will not cast and want to make sure at least this works before I go down the path of implementing everything I need in the customPrincipal. Why is this unable to cast?
public abstract class CustomWebViewPage : WebViewPage
{
public virtual new CustomPrincipal User { get { return (CustomPrincipal)base.User; } }
}
public abstract class CustomWebViewPage<TModel> : WebViewPage<TModel>
{
public virtual new CustomPrincipal User { get { return (CustomPrincipal)base.User; } }
}
public class CustomPrincipal : IPrincipal
{
public bool IsInRole(string role)
{
throw new NotImplementedException();
}
public IIdentity Identity { get; private set; }
}

I'm sorry, but it's another: Found shared references to a collection

Recently I've been adding some features to my local project, and I'm struggling with this one part. The short of it is NHibernate give me the line:
Found shared references to a collection: Page.Menus
The simple part of it is, I only want to save the relational map that binds menus to pages, which you can see the Reference below in PageMap. I should add that loading data works great, it's the saving that's killing me.
I spent a lot of time yesterday digging through here, and the good ole web, trying to find the answer, and I just kept striking out. Maybe it's bad searching on my part, but I feel I tried everything. If you know where it is can you please supply it? (thanks)
For the actual details, I've tried to simplify what's going on. I've added the PageReposity, UnitOfWork, and the proxy objects, as well as their mappings.
Where I get hazy on is the cascade, and how to save the relationship table (many to many)
For the first part, here is what happens when I save (Add). I've actually done this a few ways within the PageRepository. Since I'm strugging with the Add(), I've included it here:
public override bool Add(Page entity)
{
UnitOfWork.Save(entity);
/* I have also tried doing the following below, which doesn't help
for (var index = 0; index < entity.Menus.Count; index++)
{
UnitOfWork.Save(entity.Menus[index]);
}
*/
UnitOfWork.Commit(); // bam, error!
return true;
}
In the UnitOfWork I've setup the following in the ctor (the ISession is injected each time via ninject like so:
// DomainModule
...
Bind<ISFactory>().To<NHibernateSessionFactory>()
.InSingletonScope()
.WithConstructorArgument("connectionString", _connectWeb);
...
// Back to the UnitOfWork
...
private ISession Session { get; set; }
...
public UnitOfWork(ISFactory sessionFactory)
{
_sessionFactory = sessionFactory.GetSessionFactory();
Session = _sessionFactory.OpenSession();
Session.FlushMode = FlushMode.Never; // I have also tried FlushMode.Commit
_transaction = Session.BeginTransaction(IsolationLevel.ReadCommitted);
}
...
public void Save(object obj)
{
Session.Save(obj);
}
...
public void Commit()
{
if (!_transaction.IsActive)
{
throw new InvalidOperationException("Oops! We don't have an active transaction");
}
try
{
_transaction.Commit();
Session.Flush(); // I did this FlushMode.Never was set
}
catch (Exception exception)
{
_transaction.Rollback();
throw;
}
}
I've got 3 classes here:
Page, Menu, and Link.
public class Page : IEntity<int>
{
public virtual int Id { get; set; }
public virtual IList<Menu> Menus { get; set; }
}
public class Menu : IEntity<int>
{
public virtual int Id { get; set; }
public virtual IList<Link> Links { get; set; }
}
public class Link : IEntity<int>
{
public virtual int Id { get; set; }
public virtual DateTime CreatedDate { get; set; }
public virtual string Url { get; set; }
}
Then I also have a Mappings:
public class PageMap : ClassMap<Page>
{
public PageMap()
{
Id(x => x.Id).GeneratedBy.Native();
HasManyToMany(x => x.Menus)
.Table("MenuToPage")
.ParentKeyColumn("FkPageId")
.ChildKeyColumn("FkMenuId").Cascade.SaveUpdate(); // the cascade is new here just trying to see if it helps
}
}
public class MenuMap : ClassMap<Menu>
{
public MenuMap()
{
Id(x => x.Id); // I had .GeneratedBy.Native(); attached here too.
HasManyToMany(x => x.Links)
.Table("MenuToLinks")
.ChildKeyColumn("FkLinksId")
.ParentKeyColumn("FkMenuId")
.OrderBy("MenuOrder ASC")
.Not.LazyLoad()
.Cascade.None(); // the cascade is new here just trying to see if it helps
}
}
public class LinkMap : ClassMap<Link>
{
public LinkMap()
{
Id(x => x.Id).GeneratedBy.Native();
Map(x => x.Url);
Map(x => x.CreatedDate);
Map(x => x.ModifiedDate);
References(x => x.MetaData, "FkMetaDataId").Not.Nullable().Not.LazyLoad();
}
}
Can anyone help me or point me in a direction, I'd really appreciate your help.
Like always thank you,
Kelly
Unfortunately you have posted everything but the construction of your objects before you safe them.
Usually this error can occur if you assign the same collection of entities to different instances. For example (pseudo code)
var menuList = new List<Menu>();...
pageA.Menus = menuList;
pageB.Menus = menuList;
This would set the reference of menuList to both, pageA.Menus and pageB.Menus.
Instead, assign all items of menuList to each page with pageA.AddRange(menuList) or a loop or whatever...

Error when add Handler

I developed new module, when I add below code for handler and want to create one content from my new contentType in dashboard and submit form, I get an error. When I remove Handler or comment that the error was fixed but none part of data saved in database.
I checked, migration run OK and table created successfully. here is my model, record and part codes. Thanks...
// MyModulePart.cs
using System;
using Orchard.ContentManagement;
namespace www.MyModule.com.Models {
public class MyModule : ContentPart<MyModuleRecord> {
public string Name { get { return Record.Name; } set { Record.Name = value; } }
public string ImdbRate { get { return Record.ImdbRate; } set { Record.ImdbRate = value; } }
}
}
// MyModulePartRecord.cs
using System;
using Orchard.ContentManagement.Records;
namespace www.MyModule.com.Models
{
public class MyModulePartRecord : ContentPartRecord
{
public virtual string Name { get; set; }
public virtual string ImdbRate { get; set; }
}
}
// Migration Code
SchemaBuilder.CreateTable("MyModulePartRecord", table => table
.ContentPartRecord()
.Column<string>("Name")
.Column<string>("ImdbRate"));
// Handler Code
using Orchard.ContentManagement.Handlers;
using Orchard.Data;
using www.MyModule.com.Models;
namespace www.MyModule.com.Handlers {
public class MyModuleHandler : ContentHandler
{
public MyModuleHandler(IRepository<MyModulePartRecord> MyModulePartRepository)
{
Filters.Add(StorageFilter.For(MyModulePartRepository));
}
}
}
Error:
null id in Orchard.ContentManagement.Records.ContentItemRecord entry
(don't flush the Session after an exception occurs)
please guide me.
Excuse me for my bad English.
Thanks...

Automapper ObservableCollection – refreshing is not working

I have small WPF application. There are 5 projects in solution.
I want separate DOMAIN classes with UI ENTITIES and I want to use AUTOMAPPER.
You can download whole solution here: TestWPFAutomapper.zip
Domain class(Domain.Source.cs) with UI Entity(Entities.Destination.cs) have same signature.
In Entities.Destination.cs I would like to put other logic.
namespace DOMAIN
{
public class Source
{
public int Id { get; set; }
public int Position { get; set; }
}
}
using System.ComponentModel;
namespace ENITITIES
{
public class Destination : INotifyPropertyChanged
{
private int _id;
private int _position;
public int Id
{
get { return _id; }
set
{
_id = value;
OnPropertyChanged("Id");
}
}
public int Position
{
get { return _position; }
set
{
_position = value;
OnPropertyChanged("Position");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
My data comes from DAL.DataContext using Entity Framework with CodeFirst. Here I´m using Source class.
using System.Data.Entity;
using DOMAIN;
namespace DAL
{
public class DataContext : DbContext
{
public DbSet<Source> Sources { get; set; }
}
}
Mapping is in BL.MyAppLogic.cs . In this class I have property Items which is ObservableCollection.
After puting another item into DB for Source class collection get refresh but for Destination is not refreshing.
using System.Collections.ObjectModel;
using System.Data.Entity;
using System.Linq;
using AutoMapper;
using DAL;
using DOMAIN;
using ENITITIES;
namespace BL
{
public class MyAppLogic
{
private readonly DataContext _dataContext = new DataContext();
public ObservableCollection<Source> Items { get; set; }
//public ObservableCollection<Destination> Items { get; set; }
public MyAppLogic()
{
Database.SetInitializer(new MyInitializer());
Mapping();
_dataContext.Sources.Load();
Items = _dataContext.Sources.Local;
//Items = Mapper.Map<ObservableCollection<Source>, ObservableCollection<Destination>>(_dataContext.Sources.Local);
}
private void Mapping()
{
Mapper.CreateMap<Source, Destination>().ReverseMap();
// I tried also Mapper.CreateMap<ObservableCollection<Source>, ObservableCollection<Destination>>().ReverseMap();
}
public int GetLastItem()
{
return _dataContext.Database.SqlQuery<int>("select Position from Sources").ToList().LastOrDefault();
}
public void AddNewItem(Destination newItem)
{
_dataContext.Sources.Add(Mapper.Map<Destination, Source>(newItem));
_dataContext.SaveChanges();
}
}
}
My problem is not with mapping, that’s works good, but with refreshing collection after adding or removing items from db. If I use DOMAIN.Source class everything works, collection is refreshing. But when I’m using ENTITIES.Destination data comes from DB and also I can put som new data to DB but refresing ObservableCollection is not working.
Please try to comment lines(14 & 23) in BL.MyAppLogic.cs and uncomment(15 & 24) and you’ll see what I mean.
Thank you for any help.
I got it but I don´t know if is correct.
Local has CollectionChanged event
so in constructor I put these lines
public MyAppLogic()
{
Database.SetInitializer(new MyInitializer());
Mapping();
_dataContext.Sources.Load();
_dataContext.Sources.Local.CollectionChanged += SourcesCollectionChanged;
Items = Mapper.Map<ObservableCollection<Source>, ObservableCollection<Destination>>(_dataContext.Sources.Local);
}
and handler looks
private void SourcesCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
var source = sender as ObservableCollection<Source>;
Mapper.Map(source, Items);
}
Now is my collection automating refreshing when I put something to DB in my UI.
Looks like automapper don´t put reference into Items, but create new instance.

Resources