I am working on a school project using ASP.NET MCV4, EF6, Code-First models. Now, I am wondering how should I fill the database with sample data. I checked migrations, but I don't want to mess with the db structure. I just want to insert data, I tried this:
namespace Autokereskedes.Models
{
public class _SampleData : DropCreateDatabaseIfModelChanges<AutoDb>
{
protected override void Seed(AutoDb context)
{
new Autokereskedes.Models.SampleData.Users().List().ForEach(u=>context.Users.Add(u));
new Autokereskedes.Models.SampleData.Cars().List().ForEach(c => context.Cars.Add(c));
}
}
}
namespace Autokereskedes.Models.SampleData
{
public class Users
{
public List<User> List()
{
var crypto = new SimpleCrypto.PBKDF2();
var salt = Autokereskedes.Controllers.AccountController.PasswordSalt;
return new List<User>
{
new User {
UserId = Guid.NewGuid(),
Email = "admin#autoker.hu",
Password = crypto.Compute("admin",salt),
Phone = "+36 20 XXX YYZZ",
Banned = false,
Country = "Hungary",
City = "Szeged",
Street = "DivisonByZero street 1/0",
ZipCode = 1100,
RegistrationDate = DateTime.Now
},
new User {
UserId = Guid.NewGuid(),
Email = "user#autoker.hu",
Password = crypto.Compute("user",salt),
Phone = "+36 20 XXX YYZZ",
Banned = false,
Country = "Hungary",
City = "Szeged",
Street = "DivisonByZero street 2/0",
ZipCode = 1100,
RegistrationDate = DateTime.Now
}
};
}
}
}
It is working, I thought. But how should I insert data that has foreign keys? I saw a tutorial where they used a single file for all the List<>-s and in the foreign key field used something like this: Genre = genres.Single(g => g.Name == "Jazz"). I can't really copy that now.
namespace Autokereskedes.Models.SampleData
{
public class Cars
{
public List<Car> List()
{
return new List<Car>
{
new Car {
CarId = Guid.NewGuid(),
DepoId = now what
},
new Car {
}
};
}
}
}
When you seed the data, you need to account for the foreign key relationships... eventually.
return new List<Car>
{
new Car {
CarId = Guid.NewGuid(),
DepoId = now what // it depends, is this a required relationship?
},
new Car {
}
};
If DepoId is an optional relationship, you can just wait until you have a Depo & DepoId before setting up this property. Otherwise if it is required, you need to set it up before you insert it into the context.
protected override void Seed(AutoDb context)
{
new Autokereskedes.Models.SampleData.Users().List()
.ForEach(u=>context.Users.Add(u));
var cars = new Autokereskedes.Models.SampleData.Cars().List();
var depos = new Autokereskedes.Models.SampleData.Depos().List();
foreach (var car in cars)
{
car.DepoId = depos.FirstOrDefault(x => x.DepoId == ...?);
context.Cars.Add(car);
}
}
I suppose the question is, how do you decide which depo should be assigned to each car?
Another way to do it, since your Depo entities are a dependency and you need to resolve them first, would be to pass your depos to your cars list method:
var depos = new Autokereskedes.Models.SampleData.Depos().List();
depos.ForEach(d => context.Depos.Add(d));
//context.SaveChanges(); no need for this since your id's are Guid's
var cars = new Autokereskedes.Models.SampleData.Cars().List(depos);
public List<Car> List(IEnumerable<Depo> depos)
{
// now you have depos to look for id's in
return new List<Car>
{
new Car {
CarId = Guid.NewGuid(),
DepoId = depos.SingleOrDefault(x => [your predicate]),
},
new Car {
}
};
}
The process is called "seeding" the data.
You create an initializer object and override the Seed method:
public class MyDataContextDbInitializer : DropCreateDatabaseIfModelChanges<MyDataContext>
{
protected override void Seed(MagazineContext context)
{
context.Customers.Add(new Customer() { CustomerName = "Test Customer" });
}
}
Here is an article describing how to do it:
http://www.codeproject.com/Articles/315708/Entity-Framework-Code-First-Data-Initializers
I made an Nuget package, so you can generate random contact data (firstname, lastname, city, zipcode, birthdates, accountnumbers, etc)
In this version you can export to CSV, XML, JSON and SQL.
Open Visual Studio, Manage Nuget Packages
Search online for:
DSharp FrameWork: ContactGenerator
Any suggestions for extending functionality are welcome.
Related
I'm trying to display data from a SQL Server database. I've been struggling with it for a whole day now and still can't find any working solution or tutorial.
What I want to do - make a simple "database browser". The best thing that worked so far was this tutorial https://www.c-sharpcorner.com/article/entity-framework-database-first-in-asp-net-core2/
But I have only one table to display and I don't know how to write this part of code:
public IActionResult Index()
{
var _emplst = _dbContext.tblEmployees
.Join(_dbContext.tblSkills, e => e.SkillID, s => s.SkillID,
(e, s) => new EmployeeViewModel
{ EmployeeID = e.EmployeeID, EmployeeName = e.EmployeeName,
PhoneNumber = e.PhoneNumber, Skill = s.Title,
YearsExperience = e.YearsExperience }).ToList();
IList<EmployeeViewModel> emplst = _emplst;
return View(emplst);
}
for just one table (without any join). Everything I try ends up with an error that I cannot convert tblEmployees to EmployeeViewModel.
Could someone possibly help me? Or suggest any other solution, that might work? I really just want to drag a data from a table and display it on a web page.
EDIT:
ComponentContext.cs:
public class ComponentsContext:DbContext
{
public ComponentsContext(DbContextOptions<ComponentsContext> options) : base(options)
{
}
public DbSet<tblComponents> tblComponent { get; set; }
}
}
Your _emplst list is of a different type (class) than the type (class) EmployeeViewModel.
So you need to go through you list _emplst and transfer the values needed in EmployeeViewModel.
This can be something like this:
public IActionResult Index()
{
var _emplst = _dbContext.tblEmployees.
Join(_dbContext.tblSkills, e => e.SkillID, s => s.SkillID,
(e, s) => new EmployeeViewModel
{ EmployeeID = e.EmployeeID, EmployeeName = e.EmployeeName,
PhoneNumber = e.PhoneNumber, Skill = s.Title,
YearsExperience = e.YearsExperience }).ToList();
var emplst = _emplst.Select( e=> new EmployeeViewModel {
.. i dont known the properties ..
A = e.A,
B = e.B,
... ..
}).ToList();
return View(emplst);
}
As answer to your comment below on the tlbComponent, try this:
var _cmplist = _dbContext.tblComponent.ToList().Select(e => new ComponentsViewModel { ID = e.ID, Name = e.Name, } ).ToList();
IList<ComponentsViewModel> cmplist = _cmplist;
return View(cmplist);
i have change _dbContext.tblComponent.Select(... to _dbContext.tblComponent.ToList().Select(....
I am writing a C# app in a Xamarin.Forms project that displays a contact name, and street address. I am having trouble pulling the address from the CNContact and assigning the contacts address to a string.
Its going to be something obvious, but i'm stuck!
public List<Contact> GetContacts()
{
contactList = new List<Contact>();
var store = new Contacts.CNContactStore();
var ContainerId = new CNContactStore().DefaultContainerIdentifier;
var predicate = CNContact.GetPredicateForContactsInContainer(ContainerId);
var fetchKeys = new NSString[] { CNContactKey.Identifier, CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.Birthday, CNContactKey.PostalAddresses, CNContactKey.ImageData };
NSError error;
var IPhoneContacts = store.GetUnifiedContacts(predicate, fetchKeys, out error);
foreach(var c in IPhoneContacts)
{
var contact = new Contact();
contact.FirstName = c.GivenName;
contact.FamilyName = c.FamilyName;
if(c.PostalAddresses.Length !=0)
{
contact.StreetAddress = CNPostalAddressFormatter.GetStringFrom(c.PostalAddresses, CNPostalAddressFormatterStyle.MailingAddress);
};
contactList.Add(contact);
}
return contactList;
}
The problem is that CNPostalAddressFormatter.GetStringFrom() method expects a single CNPostalAddress object as a parameter but you're passing all addresses of a single contact since the PostalAddresses property is an array of CNLabeledValue<ValueType> objects.
What you should do is iterate over all addresses, or perhaps just take the first one by default. Really depends on what you want to achieve.
For example, this would get the first CNPostalAddress:
contact.StreetAddress = CNPostalAddressFormatter.GetStringFrom(c.PostalAddresses[0].Value, CNPostalAddressFormatterStyle.MailingAddress);
Also, if you want to know the label of the address (Home, Work etc), you can get it like this:
c.PostalAddresses[0].Label
Then the actual CNPostalAddress object is again this:
c.PostalAddresses[0].Value
Fetching Existing Contacts in iOS :
First , you need to add follow permission in Info.plist :
<key>NSContactsUsageDescription</key>
<string>This app requires contacts access to function properly.</string>
Second , you can create a model contains of needs contact info as follow :
public class ContactModel
{
public IList PhoneNumbers { get; set; }
public string GivenName { get; set; }
public string FamilyName { get; set; }
}
Third , create a func to fetch info :
public List<ContactModel> ReadContacts()
{
var response = new List<ContactModel>();
try
{
//We can specify the properties that we need to fetch from contacts
var keysToFetch = new[] {
CNContactKey.PhoneNumbers, CNContactKey.GivenName, CNContactKey.FamilyName,CNContactKey.PostalAddresses,CNContactKey.PhoneNumbers
};
//Get the collections of containers
var containerId = new CNContactStore().DefaultContainerIdentifier;
//Fetch the contacts from containers
using (var predicate = CNContact.GetPredicateForContactsInContainer(containerId))
{
CNContact[] contactList;
using (var store = new CNContactStore())
{
contactList = store.GetUnifiedContacts(predicate, keysToFetch, out
var error);
}
//Assign the contact details to our view model objects
response.AddRange(from item in contactList
where item?.EmailAddresses != null
select new ContactModel
{
PhoneNumbers = item.PhoneNumbers,
PostalAddresses = CNPostalAddressFormatter.GetStringFrom(item.PostalAddresses[0].Value, CNPostalAddressFormatterStyle.MailingAddress),
GivenName = item.GivenName,
FamilyName = item.FamilyName
});
}
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
return response;
}
Fourth , invoke func :
List<ContactModel> contacts = ReadContacts();
ContactModel contactVm;
for (int i = 0; i < contacts.Count; i++)
{
contactVm = contacts[i];
Console.WriteLine("Contact is : " + contactVm.FamilyName);
Console.WriteLine("Contact is : " + contactVm.GivenName);
Console.WriteLine("Contact is : " + contactVm.PostalAddresses);
}
...
Contact is : Taylor
Contact is : David
Contact is : 1747 Steuart Street
Tiburon CA 94920
USA
Fifth , the screenshot as follow :
===================================Udate=====================================
Your code should be modified as follow :
public List<Contact> GetContacts()
{
contactList = new List<Contact>();
var store = new Contacts.CNContactStore();
var ContainerId = new CNContactStore().DefaultContainerIdentifier;
var predicate = CNContact.GetPredicateForContactsInContainer(ContainerId);
var fetchKeys = new NSString[] { CNContactKey.Identifier, CNContactKey.GivenName, CNContactKey.FamilyName, CNContactKey.Birthday, CNContactKey.PostalAddresses, CNContactKey.ImageData };
NSError error;
var IPhoneContacts = store.GetUnifiedContacts(predicate, fetchKeys, out error);
foreach(var c in IPhoneContacts)
{
var contact = new Contact();
contact.FirstName = c.GivenName;
contact.FamilyName = c.FamilyName;
if(c.PostalAddresses.Length !=0)
{
contact.StreetAddress = CNPostalAddressFormatter.GetStringFrom(c.PostalAddresses[0].Value, CNPostalAddressFormatterStyle.MailingAddress);
};
contactList.Add(contact);
}
return contactList;
}
The property postalAddress of Method CNPostalAddressFormatter.GetStringFrom
is a type of object(Contacts.CNPostalAddress) , however c.PostalAddresses is a type of Array.
public static string GetStringFrom (Contacts.CNPostalAddress postalAddress, Contacts.CNPostalAddressFormatterStyle style);
I am following a tutorial online for ASP.NET MVC & Angular, but the author(Sourav Mondal) uses Entity to query the database. Unfortunately, I am using SQL Server 2000, and EF is not an option. The following is the code which I am attempting to transpose:
// GET: /Data/
//For fetch Last Contact
public JsonResult GetLastContact()
{
Contact c = null;
//here MyDatabaseEntities our DBContext
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
c = dc.Contacts.OrderByDescending(a => a.ContactID).Take(1).FirstOrDefault();
}
return new JsonResult { Data = c, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
This is my current speculation for an EF-less solution, supposing the Contacts have three fields in the database,ContactID, Name, and Password:
Models/Contact.cs class:
public class Contact
{
public string Name { get; set; }
public string Password { get; set; }
}
Controllers/DataController.cs,GetLastContact():
public class DataController : Controller
{
// GET: /Data/
public JsonResult GetLastContact()
{
Contact c = null;
using (SqlConnection cnxn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["TheConnectionString"].ConnectionString))
{
using (SqlCommand sqlQuery = new SqlCommand("SELECT TOP 1 ContactID FROM Northwind ORDER BY ContactID DESC "))
{
cnxn.Open();
SqlDataReader reader = sqlQuery.ExecuteReader();
while (reader.Read())
{
string contact_ID = (string)reader["ContactID"];
string first_name = (string)reader["Name"];
string password = (string)reader["Password"];
}
// Some magic here
reader.Close();
cnxn.Close();
}
}
return new JsonResult { Data = c, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
And Sourav's Angular code:
angular.module('MyApp') //extending from previously created angular module in the previous part
.controller('Part2Controller', function ($scope, ContactService) { //inject ContactService
$scope.Contact = null;
ContactService.GetLastContact().then(function (d) {
$scope.Contact = d.data; // Success
}, function () {
alert('Failed'); // Failed
});
})
.factory('ContactService', function ($http) { // here I have created a factory which is a populer way to create and configure services
var fac = {};
fac.GetLastContact = function () {
return $http.get('/Data/GetLastContact');
}
return fac;
});
I feel like although my solution is probably spaghetti, it cannot be too far off from working. Any little nudge anyone could give this code would be awesome! Or any constructive advice as to how one should proceed in stripping Entity of its Entity.
// Some magic here
c = new Contact
{
Name = first_name,
Password = password
};
// end of magic
I am not sure that you want what you want.
For me its sounds more like you want to make your own entity for your database (which does not support EF)
So just make some class of the table and get a List of it so thats it.
Little Example:
SomeClass
List allContactsInDatabase;
To Keep your Data updated use polling or just call a refresh every 30 seconds or faster/slower how you need it.
Hope thats helps
I have an Interface [BindControls] which takes data from GUI and store it into a list „ieis”.
After that, Into another class, which sends this data through WebServices, I want to take this data from „ieis” and put it into required by WS Class fields (bottom is a snippet of code)
This is the interface:
void BindControls(ValidationFrameBindModel<A.B> model)
{
model.Bind(this.mtbxTax, (obj, value) =>
{
var taxa = TConvertor.Convert<double>((string)value, -1);
if (taxa > 0)
{
var ieis = new List<X>();
var iei = new X
{
service = new ServiceInfo
{
id = Constants.SERVICE_TAX
},
amount = tax,
currency = new CurrencyInfo
{
id = Constants.DEFAULT_CURRENCY_ID
}
};
ieis.Add(iei);
}
},"Tax");
}
This is the intermediate property:
//**********
class A
{
public B BasicInfo
{
get;
set;
}
class B
{
public X Tax
{
get;
set;
}
}
}
//***********
This is the class which sends through WS:
void WebServiceExecute(SomeType someParam)
{
//into ‚iai’ i store the data which comes from interface
var iai = base.Params.FetchOrDefault<A>( INFO, null);
var convertedObj = new IWEI();
//...
var lx = new List<X>();
//1st WAY: I tried to put all data from ‚Tax’into my local list ‚lx’
//lx.Add(iai.BasicInfo.Tax); - this way is not working
//2nd WAY: I tried to put data separately into ‚lx’
var iei = new X
{
service = new ServiceInfo
{
id = iai.BasicInfo.Tax.service.id
},
amount = iai.BasicInfo.Tax.amount,
currency = new CurrencyInfo
{
id = iai.BasicInfo.Tax.currency.id
}
};
lx.Add(iei);
// but also is not working
Can you help me please to suggest how to implement a way that will fine do the work (take data from ‚ieis’ and put her into ‚lx’).
Thank you so much
As noted in my comment, it looks like iai.BasicInfo.Tax is null, once you find out why that is null your original Add() (#1) will work.
I don't know if I am doing something wrong "I think I am" or I have hit a subsonic limitation.
I have 3 tables Articles, ArticleCategories and ArticleComments with a one to many relationship between Articles the other tables.
I have created the following class
public partial class Article
{
private string _CategoryName;
public string CategoryName
{
get { return _CategoryName; }
set
{
_CategoryName = value;
}
}
public ArticleCategory Category { get;set;}
private List<System.Linq.IQueryable<ArticleComment>> _Comments;
public List<System.Linq.IQueryable<ArticleComment>> Comments
{
get
{
if (_Comments == null)
_Comments = new List<IQueryable<ArticleComment>>();
return _Comments;
}
set
{
_Comments = value;
}
}
}
I get a collection of articles using this snippet
var list = new IMBDB().Select.From<Article>()
.InnerJoin<ArticleCategory>(ArticlesTable.CategoryIDColumn, ArticleCategoriesTable.IDColumn)
.InnerJoin<ArticleComment>(ArticlesTable.ArticleIDColumn,ArticleCommentsTable.ArticleIDColumn)
.Where(ArticleCategoriesTable.DescriptionColumn).IsEqualTo(category).ExecuteTypedList<Article>();
list.ForEach(x=>x.CategoryName=category);
list.ForEach(y => y.Comments.AddRange(list.Select(z => z.ArticleComments)));
I get the collection Ok but when I try to use the comments collection using
foreach (IMB.Data.Article item in Model)
{
%>
<%
foreach (IMB.Data.ArticleComment comment in item.Comments)
{
%>
***<%=comment.Comment %>***
<%}
} %>
the comment.Comment line throws this exception
Unable to cast object of type 'SubSonic.Linq.Structure.Query`1[IMB.Data.ArticleComment]' to type 'IMB.Data.ArticleComment'.
I am basically trying to avoid hitting the database each time the comment is needed.
is there another to achieve this?
Thanks
OK - I'm not doing exactly what you're attempting but hopefully this example will bring some clarity to the situation. This is more along the lines of how I would do a join using SubSonic if I absolutely had to do it this way. The only way I would consider this approach is if I were confined by some 3rd party implementation of the object and/or database schema...
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using SubSonic.Repository;
namespace SubsonicOneToManyRelationshipChildObjects
{
public static class Program
{
private static readonly SimpleRepository Repository;
static Program()
{
try
{
Repository = new SimpleRepository("SubsonicOneToManyRelationshipChildObjects.Properties.Settings.StackOverflow", SimpleRepositoryOptions.RunMigrations);
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.ReadLine();
}
}
public class Article
{
public int Id { get; set; }
public string Name { get; set; }
private ArticleCategory category;
public ArticleCategory Category
{
get { return category ?? (category = Repository.Single<ArticleCategory>(single => single.Id == ArticleCategoryId)); }
}
public int ArticleCategoryId { get; set; }
private List<ArticleComment> comments;
public List<ArticleComment> Comments
{
get { return comments ?? (comments = Repository.Find<ArticleComment>(comment => comment.ArticleId == Id).ToList()); }
}
}
public class ArticleCategory
{
public int Id { get; set; }
public string Name { get; set; }
}
public class ArticleComment
{
public int Id { get; set; }
public string Name { get; set; }
public string Body { get; set; }
public int ArticleId { get; set; }
}
public static void Main(string[] args)
{
try
{
// generate database schema
Repository.Single<ArticleCategory>(entity => entity.Name == "Schema Update");
Repository.Single<ArticleComment>(entity => entity.Name == "Schema Update");
Repository.Single<Article>(entity => entity.Name == "Schema Update");
var category1 = new ArticleCategory { Name = "ArticleCategory 1"};
var category2 = new ArticleCategory { Name = "ArticleCategory 2"};
var category3 = new ArticleCategory { Name = "ArticleCategory 3"};
// clear/populate the database
Repository.DeleteMany((ArticleCategory entity) => true);
var cat1Id = Convert.ToInt32(Repository.Add(category1));
var cat2Id = Convert.ToInt32(Repository.Add(category2));
var cat3Id = Convert.ToInt32(Repository.Add(category3));
Repository.DeleteMany((Article entity) => true);
var article1 = new Article { Name = "Article 1", ArticleCategoryId = cat1Id };
var article2 = new Article { Name = "Article 2", ArticleCategoryId = cat2Id };
var article3 = new Article { Name = "Article 3", ArticleCategoryId = cat3Id };
var art1Id = Convert.ToInt32(Repository.Add(article1));
var art2Id = Convert.ToInt32(Repository.Add(article2));
var art3Id = Convert.ToInt32(Repository.Add(article3));
Repository.DeleteMany((ArticleComment entity) => true);
var comment1 = new ArticleComment { Body = "This is comment 1", Name = "Comment1", ArticleId = art1Id };
var comment2 = new ArticleComment { Body = "This is comment 2", Name = "Comment2", ArticleId = art1Id };
var comment3 = new ArticleComment { Body = "This is comment 3", Name = "Comment3", ArticleId = art1Id };
var comment4 = new ArticleComment { Body = "This is comment 4", Name = "Comment4", ArticleId = art2Id };
var comment5 = new ArticleComment { Body = "This is comment 5", Name = "Comment5", ArticleId = art2Id };
var comment6 = new ArticleComment { Body = "This is comment 6", Name = "Comment6", ArticleId = art2Id };
var comment7 = new ArticleComment { Body = "This is comment 7", Name = "Comment7", ArticleId = art3Id };
var comment8 = new ArticleComment { Body = "This is comment 8", Name = "Comment8", ArticleId = art3Id };
var comment9 = new ArticleComment { Body = "This is comment 9", Name = "Comment9", ArticleId = art3Id };
Repository.Add(comment1);
Repository.Add(comment2);
Repository.Add(comment3);
Repository.Add(comment4);
Repository.Add(comment5);
Repository.Add(comment6);
Repository.Add(comment7);
Repository.Add(comment8);
Repository.Add(comment9);
// verify the database generation
Debug.Assert(Repository.All<Article>().Count() == 3);
Debug.Assert(Repository.All<ArticleCategory>().Count() == 3);
Debug.Assert(Repository.All<ArticleComment>().Count() == 9);
// fetch a master list of articles from the database
var articles =
(from article in Repository.All<Article>()
join category in Repository.All<ArticleCategory>()
on article.ArticleCategoryId equals category.Id
join comment in Repository.All<ArticleComment>()
on article.Id equals comment.ArticleId
select article)
.Distinct()
.ToList();
foreach (var article in articles)
{
Console.WriteLine(article.Name + " ID " + article.Id);
Console.WriteLine("\t" + article.Category.Name + " ID " + article.Category.Id);
foreach (var articleComment in article.Comments)
{
Console.WriteLine("\t\t" + articleComment.Name + " ID " + articleComment.Id);
Console.WriteLine("\t\t\t" + articleComment.Body);
}
}
// OUTPUT (ID will vary as autoincrement SQL index
//Article 1 ID 28
// ArticleCategory 1 ID 41
// Comment1 ID 100
// This is comment 1
// Comment2 ID 101
// This is comment 2
// Comment3 ID 102
// This is comment 3
//Article 2 ID 29
// ArticleCategory 2 ID 42
// Comment4 ID 103
// This is comment 4
// Comment5 ID 104
// This is comment 5
// Comment6 ID 105
// This is comment 6
//Article 3 ID 30
// ArticleCategory 3 ID 43
// Comment7 ID 106
// This is comment 7
// Comment8 ID 107
// This is comment 8
// Comment9 ID 108
// This is comment 9
Console.ReadLine();
// BETTER WAY (imho)...(joins aren't needed thus freeing up SQL overhead)
// fetch a master list of articles from the database
articles = Repository.All<Article>().ToList();
foreach (var article in articles)
{
Console.WriteLine(article.Name + " ID " + article.Id);
Console.WriteLine("\t" + article.Category.Name + " ID " + article.Category.Id);
foreach (var articleComment in article.Comments)
{
Console.WriteLine("\t\t" + articleComment.Name + " ID " + articleComment.Id);
Console.WriteLine("\t\t\t" + articleComment.Body);
}
}
Console.ReadLine();
// OUTPUT should be identicle
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.ReadLine();
}
}
}
}
The following is my personal opinion and conjecture and can be tossed/used as you see fit...
If you look at the "Better way" example this is more along the lines of how I actually use SubSonic.
SubSonic is based on some simple principles such as
Each table is an object (class)
Each object instance has an Id (e.g. Article.Id)
Each object should have a Name (or similar)
Now if you write your data entities (your classes that are representations of your tables) in a manner that makes sense when you use SubSonic you're going to work well together as a team. I don't really do any joins when I work with SubSonic because I typically don't need to and I don't want the overhead. You start to show a good practice of "lazy-loading" the comment list property on your article object. This is good, this means if we need the comments in the consumer code, go get-em. If we don't need the comments, don't spend the time & money to go fetch them from the database. I restructured your ArticleCategory to Article relationship in a way that makes sense to me but may not suit your needs. It seemed like you agreed with Rob conceptually (and I agree with him again).
Now, there are 1000 other improvements to be made to this architecture. The first that comes to mind is to implement a decent caching pattern. For example, you may not want to fetch the comments from the database on each article, every time the article is loaded. So you might want to cache the article and comments and if a comment is added, in your "add comment" code, wipe the article from the cache so it gets rebuild next load. Categories is a perfect example of this... I would typically load something like categories (something that isn't likely to change every 5 minutes) into a master Dictionary (int being the category id) and just reference that in-memory list from my Article code. These are just basic ideas and the concept of caching, relational mapping database or otherwise can get as complicated as you like. I just personally try to adhere to the SubSonic mentality that makes database generation and manipulation so much easier.
Note: If you take a look at the way Linq2SQL does things this approach is very similar at the most basic layer. Linq2SQL typically loads your dependent relationships every time whether you wanted that or knew it was doing it or not. I much prefer the SubSonic "obviousness", if you will, of what is actually happening.
Sorry for the rant but I really hope you can run the above code in a little Console application and get a feel for what I'm getting at.
first thought, shouldn't the category association be the other way around? Category has many Articles? I don't know if that will help here - it's my first observation.
I think you're having a naming collision here. A "Structure.Query" is an object we create on the Structs.tt and it looks like that's the namespace you're referencing somehow with "item.Comments". My guess is there's a table somewhere called "Comments" that is getting confused.
Can you open up the Article class and look at the return of "Comments" property to make sure it's returning a type, and not the query?