Good afternoon friends! Help please deal with LINQ to SQL has a database with 2 tables:
CREATE TABLE [dbo].[Persons]( [Id] [int] IDENTITY(1,1) NOT NULL, [FName] [nvarchar](30) NOT NULL, [LName] [nvarchar](30) NOT NULL, [MName] [nvarchar](30) NOT NULL, CONSTRAINT [PK_Persons] PRIMARY KEY CLUSTERED ) CREATE TABLE [dbo].[Phones]( [Id] [int] IDENTITY(1,1) NOT NULL, [PId] [int] NOT NULL, [Phone] [nvarchar](30) NULL, CONSTRAINT [PK_Phones] PRIMARY KEY, CONSTRAINT FOREIGN KEY([PId]) REFERENCES [dbo].[Persons] ([Id]) ) 2 models:
[Table(Name = "Persons")] class Person { private EntitySet<Phone> _Phone; [Column(IsPrimaryKey = true)] public int Id { get; set; } [Column(Name = "FName", CanBeNull = false)] public string FirstName { get; set; } [Column(Name = "LName",CanBeNull = false)] public string LastName { get; set; } [Column(Name = "MName", CanBeNull = false)] public string MiddleName { get; set; } [Association(Storage = "_Phone")] public EntitySet<Phone> Phone { set { _Phone = value; } get { return _Phone; } } } [Table(Name = "Phones")] class Phone { private EntityRef<Person> _Person; [Column(IsPrimaryKey = true)] public int Id { get; set; } [Column(Name = "PId")] public int PersonId { get; set; } [Column(Name = "Phone", CanBeNull = true)] public string PhoneNumber { get; set; } [Association(Storage = "_Person")] public Person Person { set { _Person.Entity = value; } get { return _Person.Entity; } } } and DataContext:
class PhonebookContext : DataContext { public Table<Person> Persons { get; set; } public Table<Phone> Phones { get; set; } public PhonebookContext(string connectionString) : base(connectionString) { } } Program.cs file
class Program { public static string connectionString = ConfigurationManager.ConnectionStrings["PhonebookContext"].ConnectionString; static void Main(string[] args) { PhonebookContext db = new PhonebookContext(connectionString); /*var result = from persons in db.GetTable<Person>() join phones in db.GetTable<Phone>() on persons.Id equals phones.PersonId select new { FirstName = persons.FirstName, LastName = persons.LastName, MiddleName = persons.MiddleName, PhoneNumber = phones.PhoneNumber };*/ var result = from person in db.Persons select person; foreach (Person person in result) { Console.Write(person.FirstName + ":\t"); foreach (Phone phone in person.Phone) { Console.WriteLine(phone.PhoneNumber); } } } } on startup gives an error An unhandled exception of type 'System.ArgumentNullException' occurred in System.Core.dll
On the line where the result variable is sampled
Please tell me how to do it right.