Title: Defining relationship type using SQL Server & C#?
Tags: c#;sql;.net;sql-server
Question: How I can define relationship type(one to one, one to many, many to many) using SQL Server &amp; C#? 

I tried some ways to determine:

Attempt #1:

```DataTable foreigKeys = con.GetSchema("ForeignKeys");
```

But this get referenced tables and other things, but not relationship type...

Attempt #2:

```using (var cmd = new SqlCommand("SELECT * FROM Schema.TableName" con))
{
    using (var reader = cmd.ExecuteReader())
    using (var schemaTable = reader.GetSchemaTable())
    {
    }
}
```

And schema table don't have relationship type...It have only some column parameters like: row.Field("ColumnName"), etc...

Attempt #3:

This way was to take information with a SQL query, but I'm not a database expert so this query don't get relationship type:

```SqlCommand sqlCom = new SqlCommand("select syscolumns.name, systypes.name " + 
                                   "from syscolumns " + 
                                   "inner join systypes " +
                                   "on syscolumns.xtype = systypes.xtype AND syscolumns.xusertype = systypes.xusertype" +
                                   "where syscolumns.id = object_id('MyDataBaseTable')", con);
```

I searched all google and tried many ways, but still I will not get relationship type.. Sorry for my bad english and thanks for any help...

Comment: you will have to calculate that your self.

Comment: you could look to see if theres a middle table that only has foreign keys in it. there isn't a bullet proof way to know this by just tracking the fks.

Comment: But how to determine if relationship is one to one or many to many? Easy to determine if one to many, becouse many table will have foreign key, but one dont have...So maybe someone will help how to determine it :) Or maybe c# have tools like in datatable load relationship type :) Or with sql query determine this

Comment: If you have just a schema, and no data at all - you can (at best) guess. If there is a sufficient amount of data in the database, you could `SELECT ... GROUP BY ...` to check, whether at the time of the check, there is data to confirm the **m** or/and **n** in **1 to n** or **m to n**.



{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 0, 'CommentCount': 4, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2015:00:08/15/15', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<c#><sql><.net><sql-server>', 'Title': 'Defining relationship type using SQL Server & C#?', 'ViewCount': 79, 'id': 32024539, 'user_AboutMe': None, 'user_AccountId': 4172880.0, 'user_DisplayName': 'user3420235', 'user_Reputation': 85.0, 'user_Views': 11.0, 'user_id': 3420235.0}}