Designing Model with foreign key - repository-pattern

I am building an ORM by using Unit or Work and Repository using Dapper. I have searched the internet on this problem and no luck.
I have the following tables:
As you can see, Instance has Entity inside. I have 2 approaches:
Approach 1:
public class Entity
{
public int Id {get;set;}
public string Name {get;set;}
}
public class Instance
{
public int Id {get;set;}
public Entity Entity {get;set;}
public string Name {get;set;}
}
How can I get value for Entity with this approach?
Approach 2 (according to this link):
public class Entity
{
public int Id {get;set;}
public string Name {get;set;}
}
public class Instance
{
public int Id {get;set;}
public int EntityId {get;set;}
public string Name {get;set;}
}
Which design is better for use?

You can use QueryMultiple if you want to fetch the data from two different tables and fill it up in two different POCO classes. Following is copied from here:
string sql = "SELECT * FROM Invoice WHERE InvoiceID = #InvoiceID; SELECT * FROM InvoiceItem WHERE InvoiceID = #InvoiceID;";
using (var connection = My.ConnectionFactory())
{
connection.Open();
using (var multi = connection.QueryMultiple(sql, new {InvoiceID = 1}))
{
var invoice = multi.Read<Invoice>().First();
var invoiceItems = multi.Read<InvoiceItem>().ToList();
}
}
Both the models you mentioned in your code can be handled with this approach.
As an alternative approach, you can combine your two POCOs in one or you can use inheritance as well. But, looking at your data model, I do not think this is applicable to this particular case.
Which design is better for use?
Up to you. Whatever suits your project needs keeping down the unnecessary complexities is good for you.

Related

Unable to make general purpose query, without Domain entity

I am new to springbootneo4j. I have difficulties making general purpose queries. I want to be able to make any kind of query and get result without domain entity.
I am making a query like this in repository class:
#Query("MATCH (p:Employee) RETURN ID(p) as id, p.name as name, p.salary as salary ")
that is not working, but the following query is working:
#Query("MATCH (p:Employee) RETURN p ")
My domain entity class is something like this:
#NodeEntity
public class Employee {
#Id
#GeneratedValue
private Long id;
private String name;
private int salary;
#Relationship(type = "IS_BOSSOF", direction = Relationship.UNDIRECTED) Set<Employee> reporties = new HashSet<>();
public Employee() {}
// some more code
}
Create a command is like this:
(laksmi:Employee{name:"Laksmi",salary:200}),(ashwini:Employee{name:"AshwiniV",salary:300}), (harish:Employee{name:"Harish",salary:400}), (jay)-[:IS_BOSSOF]->(mukesh), (xyz)-[:IS_BOSSOF]->(mukesh), (harish)-[:IS_BOSSOF]->(ashwini),
Whenever you are distributing properties you need to use #QueryResult annotation on your class
SDN

neo4jClien Create node with paramaters using a List<Properties>

I am trying to create a node that takes a list of properties and uses the list object to create those properties. Is there any way to do this?
public List<PropertiesModel> node_properties;
public class PropertiesModel{
public string propertyName { get; set; }
public string propertyValue { get; set; }
}
then when I pass this on to:
client.Cypher
.Create("(n:Label {node})")
.WithParam("node", node_properties)
.ExecuteWithoutResults();
I get the following error when I run this:
CypherTypeException: Collections containing mixed types can not be stored in properties.
I am guessing since this is a list, containing a model made of strings it does not like it. Is there another way to go about building dynamic models of paramaters? I thought about IDictionary but it seems I may have issues mapping directly from a JSON post into a IDictionary.
Thanks
ok, so I am feeling slow. Just answered my own question.
I had
class nodeModel{
List<PropertiesModel> props {get; set;}
}
class PropertiesModel{
public string propertyName { get; set; }
public string propertyValue { get; set; }
}
so I needed to do:
client.Cypher
.Create("(n:Label {node})")
.WithParam("node", node_properties.props)
.ExecuteWithoutResults();
I had to step into the list basically with the .props
but this was not giving me my intended results. Say my list contained 2 properties that I was intending to have attached to 1 node. This actually created a node per property. To solve this, I mapped this over to a IDictionary.
IDictionary<string, string> map = node_properties.props.ToDictionary(p=>p.propertyname, p=>p.propertyValue);
then I changed the .WithParams part of the query statement to:
.WithParams(map)
And The intended result was 1 node made up of a list of properties.

EF6 Code First: How can I centralize content for separate sections of my site?

I want to store all our site's content in one central Content table but relate it to each section of the site. Something like:
Content (for the actual content byte[] and basic info all sections use)
ResearchArticleContent (basically has the related ContentId from the content table and extra cols for info specific to ResearchArticles)
ResearchArticle
ExecutiveContent (basically has the related ContentID from Content table and extra cols for specific data for Executives)
Executive
...and so on.
I'm having trouble understanding the whole code first approach as it pertains to ForeignKeys and InverseProperties. That's the real issue.
So, say I have these two classes as an example:
public class Content
{
[Key]
public int ContentId { get; set; }
public int ContentType { get; set; }
public byte[] ContentBytes { get; set; }
public DateTime AddedDate { get; set; }
[**`InverseProperty or ForeignKey???`**("ResearchArticleContent")]
public virtual ResearchArticleContent ResearchArticleContent { get; set; }
}
and:
public class ResearchArticleContent
{
[Key]
public int ResearchArticleContentId { get; set; }
[ForeignKey("ContentId")]
public virtual Content Content {get;set;}
public int ResearchArticleId { get; set; }
[ForeignKey("ResearchArticleId")]
public virtual ResearchArticle RelatedArticle { get; set; }
}
Where do I put the ForeignKeys / InverseProperties to relate these correctly. Because ideally, I will have Executivecontent, ResearchArticlecontent and so on for each section of the site. (I am following the precedent already laid out in a Data-First prj that I am mimicking so this is the way I have do this, fyi.)
Entity framework requires a type identifier field when you store compound objects in a single table; however, you can get around this pretty easily using views. To use views, create a single content table and a > base < class. Do not apply the TableAttribute data annotation to the base class. All other data annotations are fine.
public class ContentBase
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ContentId { get; set; }
public string Content { get; set; }
...
}
Then, you can create derived classes that more closely represent the content and apply the TableAttribute data annotation to those. For example,
[Table("ResearchArticleView")]
public class ResearchArticle : ContentBase
{
...you can add more properties here that are included in the view...
...and not necessarily the underlying table, like from a joined table...
...or just use the class as is, so that you have a better name...
}
To use this, set up a view called ResearchArticleView that includes the columns in the base class, as well as any computed or joined columns you want, then add a DbSet to your context that represents the view.
I recommend having content tables for each type of content and then use the method I've described for derived types for each content type. For example, create a base for research articles and a base for execute content. Because, when your database gets big and full of content, having one monolithic content table may cause you backup and optimization issues.

Sitecore Glass data model inheritence

I am using the Glass Mapper on a Sitecore instance where I have a basic data template structure of
Base
BaseWithList
BaseWithExtraContent
BaseWithExtraContentAndCallToActionLink
I have added model classes in my project to follow this structure too. My class names match my template names.
[SitecoreType(TemplateId = "{5D19BD92-799E-4DC1-9A4E-1DDE3AD68DAD}", AutoMap = true)]
public class Base
{
public virtual string Title {get;set;}
public virtual string Content {get;set;}
}
[SitecoreType(TemplateId = "{0491E3D6-EBAA-4E21-B255-80F0607B176D}", AutoMap = true)]
public class BaseWithExtraContent : Base
{
public virtual string ExtraContent {get;set;}
}
[SitecoreType(TemplateId = "{95563412-7A08-46A3-98CB-ABC4796D57D4}", AutoMap = true)]
public class BaseWithExtraContentAndCallToActionLink : BaseWithExtraContent
{
public virtual string CallToActionLink {get;set;}
}
These data models are used from another class that has a list of base type, I want to be able to store any derived type in here so I added attributes as detailed in this tutorial
[SitecoreType(AutoMap = true)]
public class HomePage
{
[SitecoreChildren(InferType = true)]
[SitecoreField(FieldName = "Widgets")]
public virtual IEnumerable<Base> Widgets { get; set; }
}
According to the tutorial this should work. However the list of widget just contains class of the base type.
I then found a later tutorial that said that if you have separated out the models to a different assemblies than the one Glass is installed in you have to add an AttributeConfigurationLoader pointing to the assembly your models are in. The base and derived types are all in the same assembly so I wasn't sure this would solve the issue, but I tried it anyway.
My custom loader config looks like this:
public static class GlassMapperScCustom
{
public static void CastleConfig(IWindsorContainer container)
{
var config = new Config {UseWindsorContructor = true};
container.Install(new SitecoreInstaller(config));
}
public static IConfigurationLoader[] GlassLoaders()
{
var attributes = new AttributeConfigurationLoader("Project.Data");
return new IConfigurationLoader[] {attributes};
}
public static void PostLoad(){
//Remove the comments to activate CodeFist
/* CODE FIRST START
var dbs = Sitecore.Configuration.Factory.GetDatabases();
foreach (var db in dbs)
{
var provider = db.GetDataProviders().FirstOrDefault(x => x is GlassDataProvider) as GlassDataProvider;
if (provider != null)
{
using (new SecurityDisabler())
{
provider.Initialise(db);
}
}
}
* CODE FIRST END
*/
}
}
Upon doing the custom loader config I now get an "Ambiguous match found" exception. I have checked to see if there are any other non Glass attributes set in the classes in that assembly and there aren't.
Any ideas? I guess there are 2 questions.
Why does using the inferred type attribute not load the correct types and only the base types?
Why when I attempt to solve this by adding a custom attribute loader do I get the exception?
Widgets property has two attributes - it's either mapped to the children elements of the item, or a field, can't be both.

many-to-one ForeignKeys in SQL CE db developed with EF Code First

This is my first foray in either SQL CE or EF, so I may have a lot of misunderstandings. I've searched a lot of blog entries but still can't seem to get this right.
I have an MVC3 web site for registrations for a race we're running. I have a RaceEvents table, and a Runners table, where each RaceEvent will have many runners registered it for it, i.e., Many-to-One. Here are the POCO's with extraneous data stripped out:
public class RaceEvent
{
[Required]
public int Id { get; set; }
public virtual ICollection<Runner> Runners { get; set; }
}
public class Runner
{
[Required]
public int Id { get; set; }
[Required]
public int RaceEventId { get; set;}
[ForeignKey("RaceEventId")]
public RaceEvent RaceEvent { get; set; }
}
Which, as much as I can figure out, ought to work. As I understand it, it should figure out by convention that RaceEventId is a foreign key to RaceEvents. And if that's not good enough, I'm telling it with the ForeignKey attribute.
However, it doesn't seem to be working. Whenever I insert a new runner, it is also inserting a new entry in the RaceEvents table. And when I look at the table diagram in ServerExplorer, it shows two gold keys at the top of the Runners table diagram, one for Id, identified in the properties as a PrimaryKey, and the other for RaceEventId, not identified as a PrimaryKey, but indicated in the properties to be for table Runners, rather than for table RaceEvents. I would expect a gold key for Id, but a silver ForeignKey for RaceEventId.
FWIW, I don't really care about the ICollection in the RaceEvent, but the blog entries all seemed to imply that it was necessary.
Can anybody help me get this right?
Thanks.
Ok,
Sorry I did not read your question in enough detail. In our project this is how we would represent what your doing. I looked in SSMS and it is not showing said grey key, but it does not create a race event every time you add a runner. Although you do need to make sure when you create a runner that you set the race event property.
public class DB : DbContext
{
public DB()
: base("Data Source=(local);Initial Catalog=DB;Integrated Security=True")
{
}
public IDbSet<Runner> Runners { get; set; }
public IDbSet<RaceEvent> RaceEvents { get; set; }
}
public class RaceEvent
{
[Key]
public int RaceEventID { get; set; }
}
public class Runner
{
[Key]
public int RunnerID { get; set; }
[Required]
public virtual RaceEvent RaceEvent { get; set; }
}
Any question let me know.
You need to override the model creating in the DbContext. Below is a sample for AnsNet_User & AspNet_Roles N:N relationship
protected override void OnModelCreating(DbModelBuilder dbModelBuilder)
{
dbModelBuilder.Entity<aspnet_Users>().HasMany(a => a.aspnet_Roles).WithMany(b =>
b.aspnet_Users).Map(
m =>
{
m.MapLeftKey("UserId");
m.MapRightKey("RoleId");
m.ToTable("aspnet_UsersInRoles");
});
base.OnModelCreating(dbModelBuilder);
}