How do you handle relationships to other tables with PetaPoco? - petapoco

As an example, if I have a POCO for Forum and one for ForumPost, how can I elegantly return a list of ForumPosts and specify this right in the model. I'm doing it manually now by adding my db.Query call directly in the List property, but is there a better way?
[TableName("Forum")]
[PrimaryKey("ForumID")]
[ExplicitColumns]
public class Forum : BaseModel
{
[Column]
public int ForumID { get; set; }
[Column]
public string ForumName { get; set; }
[Column]
public string ForumDescription { get; set; }
[ResultColumn]
public List<ForumPost> {
get
{
// return list of ForumPost - what's a good way to handle this?
}
}
}

I wrote an static extension to this, so I can set this in my property like this (using some of my classes). This property would be in your POCO model:
private List<AssessmentAssignment> _AssessmentAssignments;
[ResultColumn]
public List<AssessmentAssignment> AssessmentAssignments
{
get
{
return ServiceExtensions<AssessmentAssignment>.GetRelatedList(this.GetType());
}
set
{
_AssessmentAssignments = value;
}
}
Here is the ServiveExtension that I wrote up to do it, but not sure i like this yet. It works, but meh. Anyone have any better ideas?
public static class ServiceExtensions<T> where T : class, new()
{
/// <summary>
/// Experimental way to retrieve a foreign key related list with PetaPoco
/// </summary>
/// <param name="PrimaryTableType"></param>
/// <returns></returns>
public static List<T> GetRelatedList(Type PrimaryTableType)
{
var primaryTableData = PocoData.ForType(PrimaryTableType);
var relationshipTableData = PocoData.ForType(typeof(T));
using (PetaPoco.Database db = new PetaPoco.Database("ConnStringName"))
{
PetaPoco.Sql sql = new PetaPoco.Sql("SELECT A.* FROM " + relationshipTableData.TableInfo.TableName + " A")
.Append("JOIN " + primaryTableData.TableInfo.TableName + " B ON A." + primaryTableData.TableInfo.PrimaryKey + " = B." + primaryTableData.TableInfo.PrimaryKey);
return db.Fetch<T>(sql);
}
}
}

Related

How to add new language to ABP template?

I'm using free boilerplate (ASP.NET Core MVC & jQuery) from this site https://aspnetboilerplate.com/Templates
Is it possible to add new language support?
I already add localized .xml file, update 'abplanguages' table in database but it is not working. I'm changing language but text is still in english. The same situation with predefined languages already shipped with boilerplate like 'espanol-mexico' is not working but when I pick 'french' the page is translated.
This is weird because in documentation said it can be done.
https://aspnetboilerplate.com/Pages/Documents/Localization#extending-localization-sources
I wonder is it free template restriction?
inject IApplicationLanguageManager interface and use AddAsync() method to add a new language.
private readonly IApplicationLanguageManager _applicationLanguageManager;
public LanguageAppService(
IApplicationLanguageManager applicationLanguageManager,
IApplicationLanguageTextManager applicationLanguageTextManager,
IRepository<ApplicationLanguage> languageRepository)
{
_applicationLanguageManager = applicationLanguageManager;
_languageRepository = languageRepository;
_applicationLanguageTextManager = applicationLanguageTextManager;
}
protected virtual async Task CreateLanguageAsync(ApplicationLanguageEditDto input)
{
if (AbpSession.MultiTenancySide != MultiTenancySides.Host)
{
throw new UserFriendlyException(L("TenantsCannotCreateLanguage"));
}
var culture = CultureHelper.GetCultureInfoByChecking(input.Name);
await _applicationLanguageManager.AddAsync(
new ApplicationLanguage(
AbpSession.TenantId,
culture.Name,
culture.DisplayName,
input.Icon
)
{
IsDisabled = !input.IsEnabled
}
);
}
public static class CultureHelper
{
public static CultureInfo[] AllCultures = CultureInfo.GetCultures(CultureTypes.AllCultures);
public static bool IsRtl => CultureInfo.CurrentUICulture.TextInfo.IsRightToLeft;
public static bool UsingLunarCalendar = CultureInfo.CurrentUICulture.DateTimeFormat.Calendar.AlgorithmType == CalendarAlgorithmType.LunarCalendar;
public static CultureInfo GetCultureInfoByChecking(string name)
{
try
{
return CultureInfo.GetCultureInfo(name);
}
catch (CultureNotFoundException)
{
return CultureInfo.CurrentCulture;
}
}
}
public class ApplicationLanguageEditDto
{
public virtual int? Id { get; set; }
[Required]
[StringLength(ApplicationLanguage.MaxNameLength)]
public virtual string Name { get; set; }
[StringLength(ApplicationLanguage.MaxIconLength)]
public virtual string Icon { get; set; }
/// <summary>
/// Mapped from Language.IsDisabled with using manual mapping in CustomDtoMapper.cs
/// </summary>
public bool IsEnabled { get; set; }
}
I figure it out. In my case it was incorrect build action property. In VS right click on localization source file: *.xml file -> Advanced -> Build action: Embedded resource.

Using a datamember type of list

i'm new with wcf and i create a DataContract like this :
[DataContract]
public class directoriesUser
{
[DataMember]
public string NameDir { get; set; }
[DataMember]
public directoriesUser Parent { get; set; }
private ObservableCollection<directoriesUser> _userDirs = new ObservableCollection<directoriesUser>();
[DataMember]
public ObservableCollection<directoriesUser> UserDirectories
{
get { return _userDirs; }
set { _userDirs = value; }
}
}
But whe i use this class like above, the service throw an exception. can someone help me ?
public directoriesUser getHomeUser(int user_id)
{
directoriesUser dirhome = new directoriesUser();
// this doesn't works
dirhome.UserDirectories = new ObservableCollection<directoriesUser>{
new directoriesUser { NameDir = "dir1", Parent = dirhome},
new directoriesUser {NameDir = "dir2", Parent = dirhome}
};
// neither this one
dirhome.UserDirectories.Add(new directoriesUser {NameDir = "dir3", Parent = dirhome})
return dirhome;
}
Your directoriesUser class probably causes recursion when wcf serializes the instance. This is basically caused by the Parent property pointing back up the hierarchy.
Here's a more detailed article about this.

Context variables in Ninject 2

I found this article on Context Variables in an earlier version of Ninject. My question is two-fold. First, how can I get this behavior with Ninject 2? Secondly, do context variables carry through down the request chain? For example, let's say I wanted to replace these calls:
var a = new A(new B(new C())));
var specialA = new A(new B(new SpecialC()));
... with this:
var a = kernel.Get<A>();
var specialA = kernel.Get<A>(With.Parameters.ContextVariable("special", "true"));
Is it possible to set up a binding like this, where the context remembers that it is in a "special" context when it comes time to construct a C?
Here's some stuff that I use against V2, with ~0 effort to clean it up for you - let me know if you can't disentagle it.
As you surmised, there doesn't seem to be a really explicit API that surfaces the "context parameter, even for nested resolutions" stuff in v2 as-is (it's presence is buried as the 3rd parameter on an overload of the Parameter ctor).
public static class ContextParameter
{
public static Parameter Create<T>( T value )
{
return new Parameter( value.GetType().FullName, value, true );
}
}
public static class ContextParameterFacts
{
public class ProductId
{
public ProductId( string productId2 )
{
Value = productId2;
}
public string Value { get; set; }
}
public class Repository
{
public Repository( ProductId productId )
{
ProductId = productId;
}
public ProductId ProductId { get; set; }
}
public class Outer
{
public Outer( Repository repository )
{
Repository = repository;
}
public Repository Repository { get; set; }
}
public class Module : NinjectModule
{
public override void Load()
{
Bind<ProductId>().ToContextParameter();
}
}
//[ Fact ]
public static void TwoDeepShouldResolve()
{
var k = new StandardKernel( new Module() );
var o = k.Get<Outer>( ContextParameter.Create( new ProductId( "a" ) ) );
Debug.Assert( "a" == o.Repository.ProductId.Value );
}
}
And here's some code [that'll confuse the matter] which demonstrates how I apply it in my context:-
public class ServicesNinjectModule : NinjectModule
{
public override void Load()
{
Bind<ProductId>().ToContextParameter();
Bind<Func<ProductId, ResourceAllocator>>().ToConstant( ( productId ) => Kernel.Get<ResourceAllocator>(
ContextParameter.Create( productId ) ) );
}
}
public static class NinjectContextParameterExtensions
{
public static IBindingWhenInNamedWithOrOnSyntax<T> ToContextParameter<T>( this IBindingToSyntax<T> bindingToSyntax )
{
return bindingToSyntax.ToMethod( context => (T)context.Parameters.Single( parameter => parameter.Name == typeof( T ).FullName ).GetValue( context ) );
}
}
As usual, you should go look a the source and the tests - they'll provide you with a far more detailed and relevant answer than I can.

WorkItemChangedEvent and AddedRelations field

I am trying to capture links that were added to a work item in TFS by catching WorkItemChangedEvent via TFS services. Here is the relevant XML part of the message that comes through:
<AddedRelations><AddedRelation><WorkItemId>8846</WorkItemId></AddedRelation></AddedRelations>
This is declared as a field in WorkItemChangedEvent class that should be deserialized into object upon receiving the event:
public partial class WorkItemChangedEvent
{
private string[] addedRelations;
/// <remarks/>
[XmlArrayItemAttribute("WorkItemId", IsNullable = false)]
public string[] AddedRelations
{
get { return this.addedRelations; }
set { this.addedRelations = value; }
}
}
I cannot figure out why the AddedRelations does not get deserialized properly.
I can only suspect that the object structure does not match the XML schema.
I have changed the structure of my WorkItemChangedEvent class a little bit to match the XML:
public partial class WorkItemChangedEvent
{
private AddedRelation[] addedRelations;
/// <remarks/>
[XmlArrayItemAttribute("AddedRelation", IsNullable = false)]
public AddedRelation[] AddedRelations
{
get { return this.addedRelations; }
set { this.addedRelations = value; }
}
[GeneratedCodeAttribute("xsd", "2.0.50727.42")]
[SerializableAttribute()]
[DebuggerStepThroughAttribute()]
[DesignerCategoryAttribute("code")]
[XmlTypeAttribute(Namespace = "")]
public partial class AddedRelation
{
#region Fields
private string workItemId;
#endregion
/// <remarks/>
public string WorkItemId
{
get { return this.workItemId; }
set { this.workItemId = value; }
}
}
}
I still think that there must be some logic behind the original solution since it was designed by TFS authors (MS)? Anyway I am glad it works now and that I answered my question first ;]

Fluent nHibernate Automapping not creating Plural table name

I have two tables, Locations and Facilities
They map to two classes,
public Location : Entity
{
//properties
}
public Facility : Entity
{
public virtual Location Location { get; set; }
}
Everything works just dandy, until I change facility to this
public Facility : Location
{
}
Now I get an exception from nHibernate saying
NHibernate.ADOException was unhandled by user code
Message=could not execute query
InnerException: System.Data.SqlClient.SqlException
Message=Invalid object name 'Facility'.
For some reason it is not creating the plural name of the table into the sql string.
Thanks for any help!
EDIT
This is my current TableNameConvention
public class TableNameConvention : IClassConvention
{
public void Apply(FluentNHibernate.Conventions.Instances.IClassInstance instance)
{
instance.Table(Inflector.Net.Inflector.Pluralize(instance.EntityType.Name));
}
}
When Facility inherits from Entity, the Facility does run through this method. When it inherits from Location, it does not
Edit 2
Figured I'd post everything...
public class AutoPersistenceModelGenerator : IAutoPersistenceModelGenerator
{
#region IAutoPersistenceModelGenerator Members
public AutoPersistenceModel Generate()
{
var mappings = new AutoPersistenceModel();
mappings.AddEntityAssembly(typeof(Person).Assembly).Where(GetAutoMappingFilter);
mappings.Conventions.Setup(GetConventions());
mappings.Setup(GetSetup());
mappings.IgnoreBase<Entity>();
mappings.IgnoreBase(typeof(EntityWithTypedId<>));
mappings.UseOverridesFromAssemblyOf<AutoPersistenceModelGenerator>();
return mappings;
}
#endregion
private Action<AutoMappingExpressions> GetSetup()
{
return c =>
{
c.FindIdentity = type => type.Name == "Id";
};
}
private Action<IConventionFinder> GetConventions()
{
return c =>
{
c.Add<BHP.DEC.Data.NHibernateMaps.Conventions.ForeignKeyConvention>();
c.Add<BHP.DEC.Data.NHibernateMaps.Conventions.HasManyConvention>();
c.Add<BHP.DEC.Data.NHibernateMaps.Conventions.HasManyToManyConvention>();
c.Add<BHP.DEC.Data.NHibernateMaps.Conventions.ManyToManyTableNameConvention>();
c.Add<BHP.DEC.Data.NHibernateMaps.Conventions.PrimaryKeyConvention>();
c.Add<BHP.DEC.Data.NHibernateMaps.Conventions.ReferenceConvention>();
c.Add<BHP.DEC.Data.NHibernateMaps.Conventions.TableNameConvention>();
};
}
/// <summary>
/// Provides a filter for only including types which inherit from the IEntityWithTypedId interface.
/// </summary>
private bool GetAutoMappingFilter(Type t)
{
return t.GetInterfaces().Any(x =>
x.IsGenericType &&
x.GetGenericTypeDefinition() == typeof(IEntityWithTypedId<>));
}
}
Have you set a convention?
public class TableNameConvention : IClassConvention
{
public void Apply(FluentNHibernate.Conventions.Instances.IClassInstance instance)
{
string typeName = instance.EntityType.Name;
instance.Table(Inflector.Net.Inflector.Pluralize(typeName));
}
}
This is an old question, but for the sake of others who stumble upon this looking for an answer, you can also create a convention that uses the built-in PluralizationService that comes with EF:
public class TableNameConvention : IClassConvention
{
public void Apply(IClassInstance instance)
{
string typeName = instance.EntityType.Name;
instance.Table(PluralizationService.CreateService(CultureInfo.CurrentCulture).Pluralize(typeName));
}
}